Pause and resume setInterval

前端 未结 3 1313
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 20:13
window.setInterval(function(){
  //do stuff
}, milisec);

Is there a way to stop this interval at will, and to resume it from where it lasted? Say,

3条回答
  •  没有蜡笔的小新
    2020-12-04 20:40

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

提交回复
热议问题