Reputation: 97
I'm probably tired for staring at this for too long, maybe someone can clear this up for me:
//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;
}
I should be able to stop function1 and/or 2 from running after clicking the button yeah? For some reason - the ajax calls within the two functions keep running and pinging the server.
Upvotes: 0
Views: 2674
Reputation: 3926
James Montagne's answer is correct. However, if you don't want to store the ID returned by setInterval
, you can use jQuery timers plugin
$(window).everyTime(1000, "task1", function1); //set interval
$(window).stopTime("task1"); //clear interval
Upvotes: 0
Reputation: 6586
James Montagne is right, but I figured I'd code it up using what you've provided:
// 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;
}
}())
Upvotes: 1
Reputation: 8717
As James Montagne has answered above, clearInterval
takes the id returned by the setInterval
function. Please this example at mozilla developer network.
Upvotes: 0
Reputation: 78650
clearInterval
does not take a function as a parameter, it takes an ID returned by setInterval
.
var theID = setInterval(something,1000);
clearInterval(theID);
Upvotes: 4