javascript Jquery 重置 setInterval 时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27037619/
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-28 06:51:30  来源:igfitidea点击:

Jquery reset setInterval time

javascriptjquery

提问by Ben

I have a slide show use setInterval5sec, each slide should stop 5 sec.

我有一个幻灯片放映使用setInterval5 秒,每张幻灯片应停止 5 秒。

When user click previous button, slide will go back previous image.

当用户单击上一个按钮时,幻灯片将返回上一个图像。

My problem is when user click previous, time still counting. (previous image only stop 3sec not 5sec)

我的问题是当用户单击上一个时,时间仍在计数。(上图只停 3 秒而不是 5 秒)

Is any way to reset time when user click?

有什么办法可以在用户点击时重置时间?

setInterval(function(){
  //start slide...
},5000);


$('#previous').click(function(){
    //go back to previous slide and reset time
});

回答by Bhojendra Rauniyar

Like this:

像这样:

var interval;
 var timer = function(){
 interval = setInterval(function(){
  //start slide...
},5000);
};


$('#previous').click(function(){
    //go back to previous slide and reset time
   clearInterval(interval);
   timer()
});

回答by George

Put your interval-setting code in a function. Assign your interval to a globally-declared variable.

将您的间隔设置代码放在一个函数中。将您的间隔分配给全局声明的变量。

When resetting, you can clear the interval and start it again.

重置时,您可以清除间隔并重新启动。

You could start the interval on DOM load by calling startInt(), or just by triggering a click on #previous, whichever way is more appropriate for your situation.

您可以通过调用startInt()或仅通过触发单击来启动 DOM 加载间隔#previous,无论哪种方式更适合您的情况。

var myInterval = undefined,
    startInt = function(){
    myInterval = setInterval(function(){

    }, 5000);
};

$('#previous').click(function(){
    if(typeof myInterval != 'undefined'){ clearInterval(myInterval); }
    startInt();
}).click();