Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval again in 5 seconds after clearInterval button

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); 
}
like image 628
gabmadrid Avatar asked Jan 18 '23 16:01

gabmadrid


1 Answers

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
}
like image 179
nnnnnn Avatar answered Jan 20 '23 06:01

nnnnnn