Try this:
1- when you want to pause
the timer, calculate the remaining milliseconds and store it somewhere then call clearInterval
.
2- When you want to resume
the timer, just make a call to setTimeout
passing the remaining time stored in the previous step as the argument.
3- And in setTimeout
's callback you should call setInterval
again.
UPDATE: This is what you want, a changed version of javascript: pause setTimeout(); thanks to @Felix Kling
function IntervalTimer(callback, interval) {
var timerId, startTime, remaining = 0;
var state = 0; // 0 = idle, 1 = running, 2 = paused, 3= resumed
this.pause = function () {
if (state != 1) return;
remaining = interval - (new Date() - startTime);
window.clearInterval(timerId);
state = 2;
};
this.resume = function () {
if (state != 2) return;
state = 3;
window.setTimeout(this.timeoutCallback, remaining);
};
this.timeoutCallback = function () {
if (state != 3) return;
callback();
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
};
startTime = new Date();
timerId = window.setInterval(callback, interval);
state = 1;
}
Usage:
var timer = new IntervalTimer(function () {
alert("Done!");
}, 5000);
window.setTimeout(function () {
timer.pause();
window.setTimeout(function () {
timer.resume();
}, 5000);
}, 2000);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…