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.
The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that. setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms). setInterval() executes the passed function for the given time interval.
You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.
To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.
If 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With