This article analyzes the usage of js timeout calling setTimeout and intermittent calling setInterval. Share it for your reference. The details are as follows:
Today I read the book Advanced Programming (Third Edition) of JavaScript and found that setTimeout is better than setInterval, and I think it is true. I usually use setInterval to make more points, but now I’m still a little bit more thinking. 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 time.
The first parameter can be a string or a function, but it is recommended to use a function instead of a string.
Using a string is equivalent to the eval method. Causes performance losses.
clearTimeout()
The code called timeout is executed in the global scope, so the value of this in the function points to the window object in strict mode, and is undefined in strict mode.
Copy the code 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 when using timeout calls, there is no need to track the timeout call id, because after each code is executed, if another timeout call is not set, the call will stop by itself.
It is generally believed that if the timeout call is used to simulate intermittent calls, it is an optimal pattern.
In a development environment, there are few real intermittent calls because the latter intermittent calls may be initiated before the end of the previous gap call.
It is best not to use intermittent calls.
I hope this article will be helpful to everyone's JavaScript programming.