Search code examples
javascripttimeout

javascript: pause setTimeout();


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?


Solution

  • 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);
            timerId = null;
            remaining -= Date.now() - start;
        };
    
        this.resume = function() {
            if (timerId) {
                return;
            }
    
            start = Date.now();
            timerId = window.setTimeout(callback, remaining);
        };
    
        this.resume();
    };
    
    var timer = new Timer(function() {
        alert("Done!");
    }, 1000);
    
    timer.pause();
    // Do some stuff...
    timer.resume();