javascript:pause setTimeout(); [英] javascript: pause setTimeout();

查看:206
本文介绍了javascript:pause setTimeout();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个通过设置的有效超时运行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?

推荐答案

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

You could wrap window.setTimeout like this, which I think is similar to what you were suggesting in the question:

function Timer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    this.resume = function() {
        start = new Date();
        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();

这篇关于javascript:pause setTimeout();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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