javascript timer, cancel timer, and js timer optimization method

Reprinted from: http://blog.csdn.net/johnstrive/article/details/42216005

Commonly used method:

Start the timer:

[javascript]  view plain copy  
  1. window.setInterval(Method,Time)    

Method is a js method that is called regularly

Time is the interval time in milliseconds

Cancel the timer:

[javascript]  view plain copy  
  1. clearInterval(Method);  


So here comes the problem. Use clearInterval(timerid); to clear, often can not stop immediately, what method is better to solve?

The optimization scheme is as follows

[javascript]  view plain copy  
  1. var  timeout =  false // start and close buttons  
  2. function time()  
  3. {  
  4.   if(timeout) return;  
  5.   Method();  
  6.   setTimeout(time,100);  //time refers to itself, delay recursive call to itself, 100 is the interval call time, in milliseconds  
  7. }  

Summary
Generally, setInterval is not used, but the delay recursion of setTimeout is used instead of interval.
setInterval can create a stack of callbacks, especially when the time is short.  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326511772&siteId=291194637