javascript: pause setTimeout();

Hailwood picture Hailwood · Oct 19, 2010 · Viewed 113.8k times · Source

If I have an active timeout running that was set through var t = setTimeout("dosomething()", 5000),

Is there anyway to pause and resume it?


Is there any way to get the time remaining on the current timeout?
or do I have to in a variable, when the timeout is set, store the current time, then we we pause, get the difference between now and then?

Answer

Tim Down picture Tim Down · Oct 19, 2010

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();