This article mainly introduces the js timeout call setTimeout and the intermittent call setInterval. It compares and analyzes the specific usage skills of setTimeout and setInterval in the form of instances, which is very useful, for more information about how to use setTimeout and setInterval for intermittent calls, see the example in this article. Share it with you for your reference. The details are as follows:
Today, I read the javascript advanced programming (the third edition) book and found that setTimeout is better than setInterval. SetInterval is usually used for multiple points. Now let's take a look. I learned it again. The analysis is as follows:
SetTimeout contains two parameters. The first parameter is the code to be executed, and the second parameter is the time.
The first parameter can be a string or a function, but we recommend that you use a function instead of a string.
Use a string equivalent to the eval method. Performance Loss.
ClearTimeout ()
The code for timeout calls is executed in the global scope. Therefore, the value of this in the function points to the window object in strict mode and undefined in strict mode.
The Code is as follows:
// SetInval
Var num = 0;
Var max = 10;
Var intervalId = null;
Function incrementNumber (){
Num ++;
If (num = max ){
ClearInterval (innervalId );
Alert ('done ');
}
}
IntervalId = setInterval (incrementNumber (), 500 );
// SetTimeout implements the same function
Var num = 0;
Var max = 10;
Function incrementNumber2 (){
Num ++;
If (num <max ){
SetTimeout (incrementNumber2, 500 );
} Else {
Alert ('done ');
}
}
SetTimeout (incrementNumber2, 500 );
The above comparison shows that there is no need to track the timeout call id when a time-out call is used, because after each code execution, if another time-out call is no longer set, the call will be stopped on its own.
It is generally considered that a time-out call is an optimal mode to simulate intermittent calls.
In the development environment, there are few real intermittent calls, because the latter intermittent call may be started before the previous call ends.
It is best not to use intermittent calls.
I hope this article will help you design javascript programs.