So I have a timer rotates a set of images ever 5 seconds. Therefore, I am running this upon document launch.
$(document).ready(function() {
var intervalID=setInterval(function(){
rotate();
}, 5000);
});
The Rotate function simply just rotates the images. However, I also allow the user to manually select what image they are looking at. Because of this I need to cancel the SetInterval and then start it over back at 5 seconds again
What I am trying to do is cancel the interval then start it over by doing this
$('a').click(function(){
clearInterval(intervalID);
intervalID=setInterval(function(){
rotate();
}, 5000);
});
However, the code doesn't seem to reset the interval like I had hoped.
So I have a timer rotates a set of images ever 5 seconds. Therefore, I am running this upon document launch.
$(document).ready(function() {
var intervalID=setInterval(function(){
rotate();
}, 5000);
});
The Rotate function simply just rotates the images. However, I also allow the user to manually select what image they are looking at. Because of this I need to cancel the SetInterval and then start it over back at 5 seconds again
What I am trying to do is cancel the interval then start it over by doing this
$('a').click(function(){
clearInterval(intervalID);
intervalID=setInterval(function(){
rotate();
}, 5000);
});
However, the code doesn't seem to reset the interval like I had hoped.
Share Improve this question asked Jul 28, 2011 at 9:17 user646655user646655 1311 silver badge6 bronze badges 1-
1
OT: Instead of
setInterval(function(){rotate();}, 5000)
you can writesetInterval(rotate, 5000)
. – Felix Kling Commented Jul 28, 2011 at 9:21
3 Answers
Reset to default 6If the intervalID
variable is declared within the .ready()
scope, the following ought to work (untested):
$(document).ready(function() {
var rotate = function() { ... },
intervalID = setInterval(rotate, 5000);
$('a').click(function() {
clearInterval(intervalID);
intervalID = setInterval(rotate, 5000);
});
});
Just make intervalID
be global variable by declaring it outside and above all functions.
With your current code its scope is limited to $(document).ready()
method so it might cause the problem you describe.
Well, it looks like you are declaring interverID
locally within the anonymous function from your .ready()
handler. I'm actually wondering why you don't face a Reference error in your click-event handler, since intervalID
cannot be known there.
You need to make sure that this variable is available and does have a shared context for both functions. Easiest way to go, create an anonymous self invoking method around your script and declare that variable out of scope.
(function _myPrivateContext($, window, document, undefined) {
var intervalID = null;
$(document).ready(function() {
intervalID = setInterval(rotate, 5000);
});
$('a').click(function(){
clearInterval(intervalID);
intervalID = setInterval(rotate, 5000);
});
}(jQuery, window, document));