javascript: pause setTimeout();

2022-08-30 04:20:18

如果我有一个活动超时运行,该超时设置通过 ,var t = setTimeout("dosomething()", 5000)

是否有任何暂停和恢复它?


有没有办法获取当前超时的剩余时间?
还是我必须在变量中,当设置超时时,存储当前时间,然后我们暂停,得到现在和那时之间的差异?

答案 1

你可以这样包装,我认为这类似于你在问题中建议的内容:window.setTimeout

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

答案 2

像这样的东西应该可以解决问题。

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