如何清除setInterval的所有实例

How to clear all instances of a setInterval?

本文关键字:实例 setInterval 何清除 清除      更新时间:2023-09-26

setInterval:

$('li.item').live('click', function(){ 
    //Need to work with Dyn created object
    //clearInterval(itemClockInterval);
    itemClockInterval = setInterval(function() {
        deconInterval(_this.children('.timeleft'), time);
    }, 1000);
});

类"item"有多个li。当单击setInterval函数时,更新附加到特定li的时钟。

我的问题是,每次an li被点击,时钟倒计时的速度是以前的两倍,因为一个额外的间隔正在运行。我需要在新的间隔开始之前清除间隔的所有实例,但是我的解决方案都不起作用。

我注释掉了我尝试过的一件事,看到间隔直到后来才创建,这是有问题的。

使用。data()将setInterval()的结果存储在元素上,并在单击时清除。

$('li.item').live('click', function(){
    $this = $(this);
    var existing_timer = $this.data('clock');
    if (existing_timer){
        clearInterval(existing_timer);
    }
    itemClockInterval = setInterval(function() {
        deconInterval($this.children('.timeleft'), time);
    }, 1000);
    $this.data('clock', itemClockInterval);
});

使用闭包:

$('li.item').live('click', (function(){ //Need to work with Dyn created object
  var itemClockInterval;
  return function(){
    if(itemClockInterval) clearInterval(itemClockInterval);
    itemClockInterval = setInterval(function() {
            deconInterval(_this.children('.timeleft'), time);
      }, 1000);
  };
})());

或者,使用jQuery的data方法:

$('li.item').live('click', function(ev){ //Need to work with Dyn created object
  var itemClockInterval = $(ev.target).data("itemClockInterval")
  if(itemClockInterval) clearInterval(itemClockInterval);
  $(ev.target).data("itemClockInterval", setInterval(function() {
          deconInterval(_this.children('.timeleft'), time);
    }, 1000));
});

使用数据存储与该li…

$('li.item').live('click', function(){ //Need to work with Dyn created object
    var itemClockIntervalID = $(this).data("itemClockIntervalID");
    if (itemClockIntervalID != "undefined") {
        clearInterval(itemClockIntervalID);
    }
    itemClockIntervalID = setInterval(function() { deconInterval(_this.children('.timeleft'), time); }, 1000);
    $(this).data("itemClockIntervalID", itemClockIntervalID);
});

或者使用jQuery的功能为您跟踪计时器,如下所述:http://plugins.jquery.com/project/timers。它会自动维护一个jQuery对象和你的计时器之间的关联,所以它会跟踪以前的计时器,这样你就可以在设置一个新的计时器之前清除间隔。