2012-11-10 36 views
1

這是this question的後續處理,其中我發現如何使代碼每x秒重複一次。是否有可能做出可以改變這種情況的事件?即我這是爲了控制這是否重複或不復選框,所以我想我需要的是這樣的:每隔x秒重複代碼,但如果[在此處插入檢查],則不會重複代碼

$(checkbox).bind("change", function() { 
    switch(whether if it is ticked or not) { 
     case [ticked]: 
      // Make the code repeat, while preserving the ability to stop it repeating 
     case [unticked]: 
      // Make the code stop repeating, while preserving the ability to start again 
    } 
}); 

我不知道我能放什麼case秒。

+0

看起來像th對你的其他問題的答案已經解決了這個問題。 'clearInterval'允許你停止一個setInterval調用。 – j08691

+0

它讓我再次啓動它嗎? – Bluefire

+0

如果您使用上面的通用結構,那麼只要複選框被更改就會生效。 – j08691

回答

1
function fooFunc() { 
    $('#foo').text(+new Date()); 
} 
var id; 
var shouldBeStopped = false; 
$('input').change(function() { 
    if (shouldBeStopped) 
     clearInterval(id); 
    else 
     id = setInterval(fooFunc, 200); 

    shouldBeStopped = !shouldBeStopped; 
});​ 

Live DEMO

2

您可以通過將setInterval函數分配給一個變量來完成。

var interval = setInterval(function() { }, 1000); 

,然後你可以通過

clearInterval(interval); 

附:停止的setInterval 開始您的間隔時間需要調用var interval = setInterval(function() { }, 1000);再次

2

您可以停止和啓動的時間間隔:

var timer; 

function start() { 
    timer = window.setInterval(function(){ 
    // do something 
    }, 1000); 
} 

function stop() { 
    window.clearInterval(timer); 
} 

start(); 

$(checkbox).bind("change", function() { 
    if ($(this).is(':checked')) { 
    start(); 
    } else { 
    stop(); 
    } 
}); 

或者你可以有一個標誌,造成間隔跳過代碼:

var enabled = true; 

var timer = window.setInterval(function(){ 
    if (!enabled) { 
    // do something 
    } 
}, 1000); 

$(checkbox).bind("change", function() { 
    enabled = $(this).is(':checked'); 
});