问题
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.
回答1:
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.
回答2:
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);
});
});
回答3:
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));
来源:https://stackoverflow.com/questions/6856651/restarting-a-setinterval