Home  >  Article  >  Web Front-end  >  JavaScript定时器和优化的取消定时器方法_javascript技巧

JavaScript定时器和优化的取消定时器方法_javascript技巧

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

通常用的方法:
启动定时器:

复制代码 代码如下:

window.setInterval(Method,Time)   

Method是定时调用的js方法

Time是间隔时间,单位是毫秒
取消定时器:

复制代码 代码如下:

clearInterval(Method); 

那么问题来了。用 clearInterval(timerid);来清除,往往不能马上停止,用什么方法比较好解决?
优化方案如下

复制代码 代码如下:

var timeout = false; //启动及关闭按钮 
function time() 

  if(timeout) return; 
  Method(); 
  setTimeout(time,100); //time是指本身,延时递归调用自己,100为间隔调用时间,单位毫秒 

总结

一般不用setInterval,而用setTimeout的延时递归来代替interval。
setInterval会产生回调堆积,特别是时间很短的时候。 

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