javascript 每次单击按钮都重置setTimeout?

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

Reset setTimeout every button click?

javascriptjquerytimersetinterval

提问by idontknowhow

Here is my Code:

这是我的代码:

var sec = 10; 
var timer = setInterval(function() {    
    $('#timer span').text(sec--); 
}, 1000);

It sets a setTimeoutfor 10 seconds. I want to have a reset button that, clicked, calls setTimeoutagain with a 10 seconds delay.

它设置了setTimeout10 秒。我想要一个重置按钮,点击后会setTimeout延迟 10 秒再次调用。

回答by aroth

You would do this by storing the result of your setTimeout()call to some variable, and then passing the result that you stored to clearTimeout()when the button is clicked, before scheduling a new timeout and assigning it back to the same variable.

为此,您可以将setTimeout()调用结果存储到某个变量,然后在clearTimeout()单击按钮时传递存储的结果,然后再安排新的超时并将其分配回同一个变量。

Sounds a bit tricky but it's really very simple. Here is an example:

听起来有点棘手,但实际上非常简单。下面是一个例子:

http://jsfiddle.net/kzDdq/

http://jsfiddle.net/kzDdq/

回答by ?ime Vidas

HTML:

HTML:

<button id="resetButton">Reset</button>

JavaScript:

JavaScript:

var resetButton = $('#resetButton')[0],
    timerId;

function timerExpired() {
    alert('Timer expired');
}

$(resetButton).click(function() {
    clearTimeout(timerId);
    timerId = setTimeout(timerExpired, 10000);
}).triggerHandler('click');

Note: this JavaScript code should be placed inside a ready handler.

注意:此 JavaScript 代码应放置在就绪处理程序中

Live demo:http://jsfiddle.net/QkzNj/

现场演示:http : //jsfiddle.net/QkzNj/

(You can set the delay to a smaller value like 3000(3 seconds) - that will make it easier to test the demo.)

(您可以将延迟设置为较小的值,例如3000(3 秒)——这将使测试演示更容易。)

回答by user278064

<div>Div</div>

var div = document.getElementsByTagName("div")[0];

function timedMsg() {
   console.log("timeout expired.");
   div.t = setTimeout(timedMsg, 1000);    
}

timedMsg();

div.onclick = function() {
   clearTimeout(div.t);
   timedMsg();
};