如果我有一个通过 var t = setTimeout("dosomething()", 5000)
设置的活动超时运行,
无论如何暂停和恢复它?
有没有办法获得当前超时的剩余时间?
或者我必须在一个变量中,当设置超时时,存储当前时间,然后我们暂停,得到现在和那时之间的区别?
原文由 Hailwood 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果我有一个通过 var t = setTimeout("dosomething()", 5000)
设置的活动超时运行,
无论如何暂停和恢复它?
有没有办法获得当前超时的剩余时间?
或者我必须在一个变量中,当设置超时时,存储当前时间,然后我们暂停,得到现在和那时之间的区别?
原文由 Hailwood 发布,翻译遵循 CC BY-SA 4.0 许可协议
这样的事情应该可以解决问题。
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 };
}
原文由 Sean Vieira 发布,翻译遵循 CC BY-SA 3.0 许可协议
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
2 回答1.3k 阅读✓ 已解决
你可以像这样包装
window.setTimeout
,我认为这与你在问题中的建议类似: