javascript: pause setTimeout();
You could wrap window.setTimeout
like this, which I think is similar to what you were suggesting in the question:
var Timer = function(callback, delay) { var timerId, start, remaining = delay; this.pause = function() { window.clearTimeout(timerId); remaining -= Date.now() - start; }; this.resume = function() { start = Date.now(); window.clearTimeout(timerId); timerId = window.setTimeout(callback, remaining); }; this.resume();};var timer = new Timer(function() { alert("Done!");}, 1000);timer.pause();// Do some stuff...timer.resume();
Something like this should do the trick.
function Timer(fn, countdown) { var ident, complete = false; function _time_diff(date1, date2) { return date2 ? date2 - date1 : new Date().getTime() - date1; } function cancel() { clearTimeout(ident); } function pause() { clearTimeout(ident); total_time_run = _time_diff(start_time); complete = total_time_run >= countdown; } function resume() { ident = complete ? -1 : setTimeout(fn, countdown - total_time_run); } var start_time = new Date().getTime(); ident = setTimeout(fn, countdown); return { cancel: cancel, pause: pause, resume: resume };}
No. You'll need cancel it (clearTimeout
), measure the time since you started it and restart it with the new time.