Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restarting a setInterval

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.

like image 346
user646655 Avatar asked Jul 28 '11 09:07

user646655


People also ask

How do you clear setInterval?

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.

Can you pause a setInterval?

You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.

How do you stop setInterval after a condition?

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.


2 Answers

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);    
    });
});
like image 145
jensgram Avatar answered Sep 21 '22 12:09

jensgram


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.

like image 20
Shadow Wizard Hates Omicron Avatar answered Sep 19 '22 12:09

Shadow Wizard Hates Omicron