Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there is active timeout in Javascript

Is there a way to find out if there are active timers ?

I have n-timers with different durations, for example:

Timer 1 -> 2-sec

Timer 2 -> 8-sec

..

...

Timer n -> n-sec

I need to know when all timers are finished

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

Note: I need solution for this particular example because in my project there are n numbers of js files which might have timers that are declared like this example

like image 460
ToTa Avatar asked Dec 15 '15 16:12

ToTa


3 Answers

You can always add control variables.

var timer1_active = true,
    timer2_active = true;
setTimeout(function () {
    timer1_active = false;
    $("#time-out-1 span").text("Finished !");
},2000);


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

$('button').click(function(){
    //Check if all Timers are finished
    var finished = !timer1_active && !timer2_active;
});
like image 120
cor Avatar answered Sep 17 '22 19:09

cor


Here's how I'd do it, create a wrapper around the native functions

(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);

Then use it like

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

like image 9
adeneo Avatar answered Sep 24 '22 13:09

adeneo


May be this will help you.

//if n Timer then take count n
var count = 2;

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


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

 $('button').click(function(){
        //Check if all Timers are finished
        if(count==0)
        //finished
 });
like image 3
Parth Trivedi Avatar answered Sep 21 '22 13:09

Parth Trivedi