gpt4 book ai didi

javascript: 暂停 setTimeout();

转载 作者:IT王子 更新时间:2023-10-29 02:40:29 24 4
gpt4 key购买 nike

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

有没有办法暂停和恢复它?


有没有办法获取当前超时的剩余时间?
或者我必须在一个变量中,当设置超时时,存储当前时间,然后我们暂停,得到现在和那时之间的区别?

最佳答案

您可以像这样包装 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();

关于javascript: 暂停 setTimeout();,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3969475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com