javascript 在 clearInterval 按钮后 5 秒内再次 setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9029392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:22:30  来源:igfitidea点击:

setInterval again in 5 seconds after clearInterval button

javascriptjquerysetintervalclearinterval

提问by gabmadrid

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 clearIntervalon the prev/next buttons). Is there a way to use setIntervalagain after a few seconds of clicking the button?

我正在做一个自动循环幻灯片的内容滑块(通过使用 定期调用“下一个”功能setInterval)但在用户单击上一个/下一个按钮时停止(通过使用clearInterval上一个/下一个按钮)。有没有办法setInterval在点击按钮几秒钟后再次使用?

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); 
}

回答by nnnnnn

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

将您setInterval放入一个函数中,然后使用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.

之间的区别setInterval()setTimeout()setInterval()在每个时间间隔重复调用的功能,同时setTimeout()在指定延迟后只有一次调用你的函数。

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.

在下面的代码中,我添加了一个函数startCycle()。调用该函数以立即启动循环,以便它自动启动并从现有stopCycle()函数中设置的超时开始。

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
}