您的位置:首页 > Web前端

what is the difference between the setTimeout and setInterval

2010-01-28 14:50 639 查看

setTimeout or setInterval

The functions setTimeout and setInterval at first glance appear to be very similar. In fact many people writing Javascript seem to be unaware of the existance of one or the other of these two functions because they write code that uses one function where the other would have been far more appropriate. The problem is that many of the descriptions of what these two functions do don't highlight the difference between them. The definitions appear identical in many cases

In fact these two similar looking functions perform very differently. The setTimeout function delays for a specified time period and then triggers execution of a specified function. Once the function is triggered the setTimeout has finished. You can of course terminate the execution of the setTimeout before it triggers the function by using the clearTimeout function.

 

Often you will see setTimeout used at the end of a function to trigger another execution of the same function perhaps passing it different parameters. Where this is done the time from the first triggering of the function until te next will be the specified delay time plus the time taken to execute the function. Here is an example:

moreSnow();
function moreSnow() {
// content of moreSnow function
setTimeout("moreSnow()", speed);
}
The setInterval function also delays for a specified time before triggering the execution of a specific function. Where it differs is that after triggering that function the command doesn't complete. Instead it waits for the specified time again and then triggers the function again and continues to repeat this process of triggering the function at the specified intervals until either the web page is unloaded or the clearInterval function is called.

The above code using setTimeout could have been written using setInterval instead and would have looped slightly faster since the loop would not have waited for the content of the function to be processed before triggering the repetition. Here is the above code rewritten to us setInterval:

moreSnow();
setInterval("moreSnow()", speed);
function moreSnow() {
// content of moreSnow function
}
Which of the two functions that you use depends on what you are trying to achieve. If different parameters need to be passed to the function on each call or the content of the function decides whether or not to call itself again then setTimeout is the one to use. Where the function just needs triggering at regular intervals then the setInterval function may produce simpler code within the function particularly if it has multiple exit points.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息