簡體   English   中英

如何清除 setInterval 的所有實例?

[英]How to clear all instances of a setInterval?

我一直對 setInterval 有疑問:

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

class“項目”有多個li。 單擊時,setInterval function 會更新附加到該特定 li 的時鍾。

我的問題是每次單擊 li 時,時鍾的倒計時速度是以前的兩倍,因為正在運行一個額外的間隔。 我需要在新間隔開始之前清除間隔的所有實例,但我的解決方案都不起作用。

我注釋掉了我嘗試過的一件事,好像直到后來才創建間隔,這是有問題的。

將 setInterval() 的結果存儲在 using.data() 元素上,並在單擊時清除它。

$('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 的數據方法:

$('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關聯的intervalID ...

$('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 object 和您的計時器之間的關聯,因此它會跟蹤前一個計時器,以便您可以在設置新計時器之前清除間隔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM