gpt4 book ai didi

javascript - 检查Javascript中是否存在事件超时

转载 作者:可可西里 更新时间:2023-11-01 02:37:38 25 4
gpt4 key购买 nike

有没有办法查明是否有事件的定时器?

我有 n 个持续时间不同的计时器,例如:

Timer 1 -> 2-sec

Timer 2 -> 8-sec

..

...

Timer n -> n-sec

我需要知道所有计时器何时结束

HTML

<div id="time-out-1">
Time out 1:<span></span>
</div>

<div id="time-out-2">
Time out 2:<span></span>
</div>

<button>
Are all timers finished ?
</button>

JS

setTimeout(function () {
$("#time-out-1 span").text("Finished !");
},2000);


setTimeout(function () {
$("#time-out-2 span").text("Finished !");
},8000);

$('button').click(function(){
// if all timers are finished
// do something
});

Jsfidle

注意:我需要这个特定示例的解决方案,因为在我的项目中有 n 个 js 文件,这些文件可能具有像这个示例一样声明的计时器

最佳答案

这是我的做法,围绕原生函数创建一个包装器

(function(w) {
var active = {};

var _setTimeout = w.setTimeout;
var _clearTimeout = w.clearTimeout;

w.setTimeout = function(fn, delay) {
var id = _setTimeout(function() {
fn();
delete active[id];
}, delay);
active[id] = true;
return id;
}

w.clearTimeout = function(id) {
delete active[id];
_clearTimeout(id);
}

w.activeTimers = function() {
return Object.keys(active).length > 0;
}
})(window);

然后像这样使用它

setTimeout(function () {
$("#time-out-1 span").text("Finished !");
},2000);


setTimeout(function () {
$("#time-out-2 span").text("Finished !");
},8000);

$('button').click(function(){
if ( window.activeTimers() ) {
// still something going on
} else {
// all done !
}
});

FIDDLE

关于javascript - 检查Javascript中是否存在事件超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34294544/

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