setInterval again in 5 seconds after clearInterval button

gabmadrid picture gabmadrid · Jan 27, 2012 · Viewed 11.3k times · Source

I'm doing a content slider that automatically cycles slides (by periodically calling the "next" function using setInterval)but stops when the user click on a prev/next buttons (by using clearInterval on the prev/next buttons). Is there a way to use setInterval again after a few seconds of clicking the button?

Code:

// start to automatically cycle slides
var cycleTimer = setInterval(function () {
   $scroll.trigger('next');
}, 450);

// set next/previous buttons as clearInterval triggers 
var $stopTriggers = $('img.right').add('img.left'); // left right

// function to stop auto-cycle
function stopCycle() {
   clearInterval(cycleTimer); 
}

Answer

nnnnnn picture nnnnnn · Jan 27, 2012

Put your setInterval in a function and then call that function with setTimeout().

The difference between setInterval() and setTimeout() is that setInterval() calls your function repeatedly at each interval, while setTimeout() calls your function only once after the specified delay.

In the code below I've added a function startCycle(). Call that function to, well, start the cycle, both immediately so that it starts automatically and from a timeout set within your existing stopCycle() function.

var cycleTimer;

function startCycle() {
   cycleTimer = setInterval(function () {
      $scroll.trigger('next');
   }, 450);
}

// start to automatically cycle slides
startCycle();

// set next/previous buttons as clearInterval triggers 
var $stopTriggers = $('img.right').add('img.left'); // left right

// function to stop auto-cycle
function stopCycle() {
   clearInterval(cycleTimer);
   setTimeout(startCycle, 5000); // restart after 5 seconds
}