This article explains the difference between JavaScriptSetInterval and setTimeout, and uses the sample code to demonstrate the same syntax for using setTimeout and setInterval. They all have two parameters: one is the code string to be executed, and the other is the interval in milliseconds. after that period, the code will be executed.
However, there are differences between the two functions. After the setInterval code is executed, it automatically repeats the code after the fixed interval, setTimeout only executes the code once.
Differences:
Window. setTimeout ("function", time); // sets a time-out object, which is executed only once and has no cycle
Window. setInterval ("function", time); // you can specify a timeout object. The period is set to 'interaction time'
Stop timing:
Window. clearTimeout (object) Clear the setTimeout object that has been set
Window. clearInterval (object) Clear the setInterval object that has been set
The Code is as follows:
PerRefresh ();
Function PerRefresh (){
Var today = new Date ();
Alert ("The time is:" + today. toString ());
SetTimeout ("showTime ()", 5000 );
}
Once this function is called, the time is displayed every five seconds.
The Code is as follows:
SetInterval ("PerRefresh ()", 5000 );
Function PerRefresh (){
Var today = new Date ();
Alert ("The time is:" + today. toString ());
}
While setInterval is not bound by the function called by itself, it simply repeats the function at a certain time.
If setInterval ("PerRefresh ()", 5000) is called, The PerRefresh function is executed every five seconds.
If you want to execute an action accurately after a fixed interval, you 'd better use setInterval. If you don't want to interfere with each other due to continuous calls, in particular, each function call requires heavy computing and a long processing time, so it is best to use setTimeout.
SetInterval continues to execute the Specified Code until clearInterval is called to clear the timer object
SetTimeout: run the specified code once and clear the timer object using clearTimeout.
Both setInterval and setTimeout return the timer object identifier for clearInterval and clearTimeout calls.