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); 
}
有帮助吗?

解决方案

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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top