最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reset setTimeout every button click? - Stack Overflow

programmeradmin5浏览0评论

Here is my Code:

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

It sets a setTimeout for 10 seconds. I want to have a reset button that, clicked, calls setTimeout again with a 10 seconds delay.

Here is my Code:

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

It sets a setTimeout for 10 seconds. I want to have a reset button that, clicked, calls setTimeout again with a 10 seconds delay.

Share Improve this question edited Apr 15, 2013 at 8:05 franzlorenzon 5,9436 gold badges37 silver badges58 bronze badges asked Jul 31, 2011 at 12:54 idontknowhowidontknowhow 1,5275 gold badges17 silver badges23 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

HTML:

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

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.

Live demo: http://jsfiddle/QkzNj/

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

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.

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

http://jsfiddle/kzDdq/

<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();
};
发布评论

评论列表(0)

  1. 暂无评论