Reynish Reynish - 1 month ago 18
jQuery Question

Reset setinterval on click

I've written this simple Carousel. At the moment I'm using setInterval to run my nextSlide function at certain intervals. I want to defer the timer from running when a user clicks on the navigation links for a certain length of time.

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

Any feedback on how the rest is written would be good too.

Answer

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

The interval part is here:

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

I made some other tweaks as well though, for example you can use a switch statement to make .nextSlide() much more readable and cheaper.

Overall though, there's no reason to make these functions as extension methods on jjquery itself since they don't interact with objects, they can just be methods scoped to the closure like this: http://jsbin.com/uzixi3/6/edit

If the methods were actually running on $('#slideContainer'), e.g. $('#slideContainer').nextSlide() and inside your methods you used this.animate() and this.css() it might make a bit more sense, just some thoughts that may help you get more flexible as you go.

Comments