The syntax of setTimeout and setInterval are the same. They all have two parameters, one is the code string to be executed, and the other is the time interval in milliseconds after which the code will be executed.
However, there is a difference between the two functions. After executing the code once, setInterval will automatically execute the code repeatedly after a fixed time interval, while setTimeout only executes that code once.
Difference:
window.setTimeout("function",time);//Set a timeout object, executed only once, no cycle
window.setInterval("function",time);//Set a timeout object Timeout object, period = 'Interaction time'
Stop timing:
window.clearTimeout(object) Clear the setTimeout object
window.clearInterval(Object) Clear the setInterval object
PerRefresh();
function PerRefresh() {
var today = new Date();
alert("The time is: " today.toString());
setTimeout("showTime()", 5000);
}
Once this function PerReflesh is called, the time will be displayed every 5 seconds
setInterval("PerRefresh()", 5000);
function PerRefresh() {
var today = new Date();
alert(" The time is: " today.toString());
}
And setInterval is not bound by the function it calls. It simply executes it repeatedly at a certain time. that function.
As long as the setInterval("PerRefresh()", 5000) function is called, the PerRefresh function will be executed every 5 seconds.
If you need to perform an action accurately after every fixed time interval, then it is best to use setInterval. If you do not want to cause mutual interference due to continuous calls, especially each function call requires heavy calculations. and long processing time, then it's better to use setTimeout.
setInterval continues to execute the specified code until clearInterval is called to clear the timer object.
setTimeout executes the specified code once and uses clearTimeout to clear the timer object.
Both setInterval and setTimeout return the timer object identifier, which is used for clearInterval and clearTimeout. call