关于启动定时器和取消定时器的问题

在js机制中,我们都知道,一般代码写在某个事件中的话,只有当触发事件,才会执行代码,比如

$(selector).click(function(){alert('你好')});

如上代码,只有在触发点击事件的时候,才会弹出 “你好” 的问候语;

但是,在使用定时器的时候,不管是事件中,还是事件外,都会在加载的时候被执行,比如

var timer = setInterval(play,speed);
$('selector').hover(function(){
   clearInterval(timer); 
},function(){
   timer = setInterval(play,speed); 
})

以上代码,我是在事件外开启了一个定时器,当鼠标经过selector的时候,关闭定时器,鼠标离开selector的时候,又会开启定时器。

可是,上面的代码会开启两个定时器,而不是我们想要的只是开启一个,那么,如果下改造后

var timer = setInterval(play,speed);
$('selector').hover(function(){
   clearInterval(timer); 
},function(){
   clearInterval(timer); 
   timer = setInterval(play,speed); 
})

记住,写在事件中的定时器,也会被加载的时候所开启,所以,务必在执行定时器的前面加上清除定时器。

原文地址:https://www.cnblogs.com/yesw/p/4607751.html