Restart setInterval

So, I have a timer that rotates a set of images every 5 seconds. So I run this when I start the document.

$(document).ready(function() { var intervalID=setInterval(function(){ rotate(); }, 5000); }); 

The Rotate function simply rotates the images. However, I also allow the user to manually select which image they are looking at. Because of this, I need to cancel SetInterval and then run it again again after 5 seconds

What I'm trying to do is cancel the interval and then start it by doing this

 $('a').click(function(){ clearInterval(intervalID); intervalID=setInterval(function(){ rotate(); }, 5000); }); 

However, the code does not seem to reset the interval as I hoped.

+6
source share
3 answers

Just make the intervalID global variable by declaring it outside and above all functions.

With your current code, its scope is limited to $(document).ready() , so there may be a problem that you are describing.

+4
source

If the intervalID variable is declared in the .ready() scope, the following should work (not verified):

 $(document).ready(function() { var rotate = function() { ... }, intervalID = setInterval(rotate, 5000); $('a').click(function() { clearInterval(intervalID); intervalID = setInterval(rotate, 5000); }); }); 
+4
source

Well, it looks like you are declaring interverID locally in an anonymous function from your .ready() handler. I really wonder why you don't encounter a Reference error in your click event handler, since the intervalID cannot be known there.

You need to make sure that this variable is accessible and has a common context for both functions. The easiest way to do this is to create an anonymous self-starting method around your script and declare this 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)); 
+3
source

Source: https://habr.com/ru/post/893759/


All Articles