JavaScript timer and optimized cancel timer methods


Common methods: Start the timer:

window.setInterval(Method,Time)   

Method is the js method that is called periodically

Time is the interval in milliseconds Cancel the timer:

clearInterval(Method); 

So here’s the problem. Use clearInterval (timerid); To clear, often cannot stop immediately, with what method better solve? The optimization scheme is as follows

var timeout = false; // Start and close buttons  
function time() 

  if(timeout) return
  Method(); 
  setTimeout(time,100); //time Refers to itself , Delay recursively calls itself ,100 Is the interval call time , Unit of milliseconds  

conclusion

setInterval is generally not used, but setTimeout’s delayed recursion instead of interval. setInterval can cause callback accumulation, especially if the time is very short.