有没有办法找出是否有活跃的计时器?
我有不同持续时间的n计时器,例如:
Timer 1 -> 2-sec Timer 2 -> 8-sec .. ... Timer n -> n-sec
我需要知道所有计时器何时完成
HTML
Time out 1:Time out 2:
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 ! } });
小提琴