如何停止setInterval? [英] How to stop setInterval?
本文介绍了如何停止setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<span id="ccc">10</span> <span id="start">start</span> <span id="stop">stop</span>
$('#start').click(function(){
var c = $('#ccc').text();
var inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function(){
clearInterval(inter);
});
我必须如何重写才能正确使用STOP?
how i must rewrite this for correctly use STOP?
LIVE: http://jsfiddle.net/c3hZh/
推荐答案
inter
必须在这两个功能的范围内.用闭包将这两个函数包装起来,这样就可以避免用新变量污染全局名称空间.
inter
needs to be in-scope for both functions. Wrap both functions with a closure so that you can avoid polluting the global namespace with a new variable.
(function ($) {
var inter;
$('#start').click(function(){
var c;
c = parseInt($('#ccc').text()); //make sure you're getting a numeric value
//don't forget to clear any existing interval before setting a new one:
if (inter) {
clearInterval(inter);
}
inter = setInterval(function() {
c--;
$('#ccc').text(c);
}, 1000);
});
$('#stop').click(function() {
clearInterval(inter);
});
}(jQuery));
这篇关于如何停止setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文