每隔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

 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; });​ 

现场演示

您可以通过将setInterval函数分配给变量来完成此操作。

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

然后你可以停止setInterval

 clearInterval(interval); 

ps开始你的间隔你需要调用var interval = setInterval(function() { }, 1000); 再次

您可以停止并开始间隔:

 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'); });