Home > Web Front-end > JS Tutorial > js timeout call setTimeout and intermittent call setInterval instance analysis_javascript skills

js timeout call setTimeout and intermittent call setInterval instance analysis_javascript skills

WBOY
Release: 2016-05-16 16:17:35
Original
1314 people have browsed it

This article analyzes the usage of js timeout call setTimeout and intermittent call setInterval. Share it with everyone for your reference. The details are as follows:

I read the book JavaScript Advanced Programming (Third Edition) today and found that setTimeout is better than setInterval, and I think it is true. I usually use setInterval more, but now I have to change my mind. Learned 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 it is recommended to use functions instead of strings.
Using strings is equivalent to the eval method. resulting in performance loss.

clearTimeout()

The code called with 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 code 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 when using timeout calls, there is no need to track the timeout call id, because after each execution of the code, if another timeout call is not set, the call will stop on its own.

It is generally believed that if timeout calls are used to simulate intermittent calls, it is the best mode.

In a development environment, true intermittent calls are rare because a later intermittent call may start before the previous intermittent call ends.

It is best not to use intermittent calls.

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template