我可能已经厌倦了长时间盯着这个, 也许有人可以为我解决这个问题:
//scripts in whispers are setup this way.
var something = function(){
setInterval(function1,1000);
setInterval(function2,1000);
blah .. blah...
}
//function2 is the same as this one
var function1 = function(){
ajax to do something on server
blah...
blah...
}
//button to stop things from running anymore
$('.stop').live('click',function(){
clearInterval(function1);
clearInterval(function2);
return false;
}
我应该能够停止运行后的function1和/或2 点击按钮是啊?由于某种原因 - ajax调用 两个函数继续运行并ping服务器。
答案 0 :(得分:4)
clearInterval
不接受函数作为参数,它接受setInterval
返回的ID。
var theID = setInterval(something,1000);
clearInterval(theID);
答案 1 :(得分:1)
// declaring this as a closure, so
// that your timers are kept out of the global namespace
(function (){
var timer1,
timer2;
// declaring 'something' this way makes it private
// use this.something if you want to be able to access this publicly
var something = function(){
timer1 = setInterval(function1, 1000);
timer2 = setInterval(function2, 1000);
// blah .. blah...
}
//function2 is the same as this one
var function1 = function(){
// ajax to do something on server
// blah...
// blah...
}
// button to stop things from running anymore
$('.stop').on('click', function(e) {
// kill out our timers
clearInterval(timer1);
clearInterval(timer2);
// prevent the browsers default click action
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
}())
答案 2 :(得分:0)
正如James Montagne上面回答的那样,clearInterval
获取了setInterval
函数返回的id。请在mozilla开发者网络上查看此example。
答案 3 :(得分:0)
James Montagne的回答是正确的。但是,如果您不想存储setInterval
返回的ID,则可以使用jQuery timers插件
$(window).everyTime(1000, "task1", function1); //set interval
$(window).stopTime("task1"); //clear interval