This article analyzes the usage of JS timeout call settimeout and intermittent call setinterval. Share to everyone for your reference. Specifically as follows:
Today, I read the JavaScript Advanced Program Design (third edition) book, found that settimeout than setinterval better, that is true. Usually use setinterval more points, now or turn the train of thought. I learned it again. The analysis is as follows:
SetTimeout contains two parameters, the first parameter is the code to execute, and the second parameter is time.
The first argument can be a string or a function, but it is recommended that you use a function instead of a string.
Using a string is equivalent to the Eval method. result in performance loss.
Cleartimeout ()
The code for the timeout call 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
Copy Code 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 to achieve 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 comparison shows that there is no need to trace the timeout call ID when using the timeout call, because once the code is executed, the call stops itself if another timeout call is no longer set.
It is generally assumed that a time-out call is the best model for simulating intermittent calls.
In the development environment, there are few real intermittent calls, because the latter intermittent call may start before the end of the previous gap call.
It is best not to use intermittent calls.
I hope this article will help you with your JavaScript programming.