暂停并恢复setInterval [英] Pause and resume setInterval

查看:439
本文介绍了暂停并恢复setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

window.setInterval(function(){
  //do stuff
}, milisec);

是否有一种方法可以随意停止此间隔,并从持续的时间继续恢复?假设代码每5秒运行一次.我在第二秒的中间将其停止,恢复后,我希望它继续运行剩余的3秒钟,然后每5秒钟继续运行一次.再次.

Is there a way to stop this interval at will, and to resume it from where it lasted? Say, code runs every 5 sec. I stop it in the middle of the 2nd second, when resumed, I want it to run the remaining 3 seconds and continue to run afterwards every 5 sec. again.

推荐答案

尝试一下:

1-当您想要pause计时器时,计算剩余的毫秒数并将其存储在某个地方,然后调用clearInterval.

1- when you want to pause the timer, calculate the remaining milliseconds and store it somewhere then call clearInterval.

2-当要使用resume计时器时,只需调用setTimeout并传递上一步中存储的剩余时间作为参数即可.

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-在setTimeout的回调中,您应该再次调用setInterval.

3- And in setTimeout's callback you should call setInterval again.

更新:这就是您想要的, javascript的更改版本:暂停setTimeout(); 感谢@Felix克林(Kling)

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

用法:

    var timer = new IntervalTimer(function () {
        alert("Done!");
    }, 5000);

    window.setTimeout(function () {
        timer.pause();
        window.setTimeout(function () {
            timer.resume();
        }, 5000);
    }, 2000);

这篇关于暂停并恢复setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆