Home  >  Article  >  Web Front-end  >  JavaScript timers and optimized cancel timer methods_javascript tips

JavaScript timers and optimized cancel timer methods_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:51:361393browse

Usually used method:
Start timer:

Copy code The code is as follows:

window.setInterval(Method,Time)

Method is a js method called regularly

Time is the interval time, the unit is milliseconds
Cancel timer:

Copy code The code is as follows:

clearInterval(Method);

Then the question comes. When clearInterval(timerid); is used to clear, it often cannot be stopped immediately. What method is better to solve it?
The optimization plan is as follows

Copy code The code is as follows:

var timeout = false; //Start and close buttons
function time()
{
if(timeout) return;
Method();
setTimeout(time,100); //time refers to itself, the delay recursively calls itself, 100 is the interval calling time, in milliseconds
}

Summary

Generally, setInterval is not used, but the delayed recursion of setTimeout is used instead of interval.
setInterval will produce callback accumulation, especially when the time is short.

Statement:
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