Reset setinterval on click

I wrote this simple carousel. Right now I'm using setInterval to run my nextSlide function at regular intervals. I want to delay the timer from starting when the user clicks on the navigation links for a certain period of time.

Check here http://jsbin.com/uzixi3/3/edit

Any feedback on how the rest is written is also good.

+7
jquery
source share
4 answers

You can do something like this: http://jsbin.com/uzixi3/5/edit

Here is the interval:

var int = setInterval($.fn.nextSlide, 3000); $("#slideNavigation a").click(function() { clearInterval(int); setTimeout(function() { setInterval($.fn.nextSlide, 3000); }, 10000); }); 

I made some other adjustments, although, for example, you can use the switch to make .nextSlide() more readable and cheaper.

In general, there is no reason to make these functions as extension methods in jjquery itself, since they do not interact with objects, they can simply be methods covered by closure as follows: http://jsbin.com/uzixi3/6/edit

If the methods were actually executed on $('#slideContainer') , for example. $('#slideContainer').nextSlide() and inside your methods that you used this.animate() and this.css() , this might make a little more sense, but just some thoughts that can help you become more flexible , When you go.

+12
source share

You can save the return value of setInterval in a variable to refer to it later - this way you can cancel it if you need, or restart it.

See this MDC article for more details.

The basics:

 intervalID = setInterval(flashText, 1000); //do something... clearInterval(intervalID); 
+5
source share

This code really helped. Thanks Nick. I made a few minor adjustments so that after pressing this function the timer stops, the function executes, and then the timer starts and resumes regular intervals.

make sure you reassign var int to the new interval created in the click function .

 var int = setInterval(change_slide, 5000); $("#div").click(function() { console.log('clicked'); clearInterval(int); setTimeout(function() { int = setInterval(change_slide, 5000); }); }); 
0
source share

Cm:

 var IntID = setTimer(); function setTimer(){ i = setInterval(startSlider, 4000); return i; } function stopSlider() { clearInterval(IntID); } //Restart Timer // Option 1 make a restartSlider function and call it $("#button").click(restartSlider); function restartSlider(){ IntID = setTimer(); } //Option 2 create an anonymous function only for that click event. $("#button").click(function(){ IntID = setTimer(); }); 
0
source share

All Articles