The difference is that setInterval will execute the code every specified time period, which is repetitive. And setTimeout will only be executed once after being called.
The following is a deep understanding of the two functions through the establishment of the function and the automatic deletion of the function;
1. The establishment of the function
The establishment of setTimeOut:
showTime();
function showTime()
{
var today = new Date();
alert("The time is: " today.toString());
setTimeout("showTime()", 5000);
}
The showtime function will be executed only five seconds after calling the function
Establishment of setInterval
setInterval("showTime()", 5000);
function showTime()
{
var today = new Date();
alert("The time is: " today.toString());
}
Summary: It seems that the results of the two functions are similar, but in fact, otherwise the second function will repeatedly report the time until the web page is closed.
Elimination of two functions:
The elimination of setTimeout uses the
clearTimeout() function; call example:
var timeoutProcess = setTimeout("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, "click", stopGoal, false);//Add the event function, the parameters are (target; event; function called; whether to bubble)
function stopGoal()
{
clearTimeout(timeoutProcess);
}
Elimination of setInterval
var timeoutProcess = setTimeout("alert('GOAL!')", 3000);
var stopGoalLink = document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink, " click", stopGoal, false);//Add the event function, the parameters are (target; event; function called; whether to bubble)
function stopGoal()
{
clearInterval(timeoutProcess);
}