JS: setInterval and clearIntervals with jQuery
JS: setInterval and clearIntervals with jQuery
我可能盯着这个看太久了,也许有人能帮我澄清一下:
//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;
}
我应该能够停止函数1和/或2从运行后点击按钮,对吗?的ajax调用两个函数继续运行并ping服务器。
clearInterval
不接受函数作为参数,它接受setInterval
返回的ID。
var theID = setInterval(something,1000);
clearInterval(theID);
James Montagne是对的,但我想我应该使用您提供的代码:
// 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;
}
}())
正如James Montagne在上面回答的那样,clearInterval
取setInterval
函数返回的id。请在mozilla开发人员网络上查看这个示例。
James Montagne的答案是正确的。然而,如果你不想存储setInterval
返回的ID,你可以使用jQuery定时器插件
$(window).everyTime(1000, "task1", function1); //set interval
$(window).stopTime("task1"); //clear interval
相关文章:
- Replacing jQuery.bind with jQuery.on
- PHP $_GET with jQuery $.get call
- Rails 3 if statement with jQuery?
- Trouble with jquery .append
- Javascript setTimeout function with JQuery
- Like Unlike toggle button with jQuery's AJAX
- IE8 issue with jQuery attr()
- ltrim with jQuery?
- json foreach array of arrays with jquery
- Setting Javascript along with JQuery
- XML to HTML with jQuery
- JQuery.animate(): HTML5 annimation with JQuery
- Bootstrap Contact Form with jQuery Validation and AJAX
- HTTP GET request with JQuery
- JavaScript Date with jQuery Countdown
- iframe Fade Out/In with jQuery
- Knockout with jquery.tmlp
- HREF within an IFrame with JQuery
- Coloring tr with jQuery
- ajax post with jquery to mongodb