检查Javascript中是否存在活动超时

ToT*_*oTa 11 javascript jquery settimeout

有没有办法找出是否有活跃的计时器?

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

Timer 1 -> 2-sec

Timer 2 -> 8-sec

..

...

Timer n -> n-sec
Run Code Online (Sandbox Code Playgroud)

我需要知道所有计时器何时完成

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>
Run Code Online (Sandbox Code Playgroud)

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
 });
Run Code Online (Sandbox Code Playgroud)

Jsfidle

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

ade*_*neo 9

这是我如何做到这一点,创建一个围绕本机函数的包装器

(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);
Run Code Online (Sandbox Code Playgroud)

然后就像使用它一样

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 !
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴