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.
3 Answers
Reset to default 8HTML:
<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();
};