Was clearTimeout successful?

Is there any way to verify clearTimeout was successful.

I have a javascript function that runs at intervals of 30 seconds asynchronously. This is a self-consistent function and uses setTimeout () to repeat in a loop. In a specific case, I need to call this function after the occurrence of an event. So I clearTimeout first and call the function again. But I do not know if I was able to successfully clear the previous cycle, or I started two separate cycles. Can I do something like this?

if(clearTimeout(timer)) alert("cleared"); 
+4
source share
2 answers

"Is there a way to verify clearTimeout was successful."

No, there is no state that you can check, but if you manage your timers correctly, this should not be a problem.


You can create your own stateful timer object, I suppose ...

 var _slice = Array.prototype.slice; // substitute for setTimeout function myTimer(fn,ms) { var args = _slice.call(arguments,2), timer_state = { complete: false, timer: setTimeout(function() { timer_state.complete = true; fn.apply(this, args); }, ms) }; return timer_state; }; // substitute for clearTimeout function clearMyTimer(timer_obj) { timer_obj.complete = true; clearTimeout(timer_obj.timer); }; 

Example of clearing a timer ...

  // create a timer var timer = myTimer( function() { console.log('timer is done'); }, 1000); console.log( timer.complete ); // complete? false clearMyTimer( timer ); // clear it console.log( timer.complete ); // complete? true 

Run permission example ...

  // create a timer var timer = myTimer( function() { console.log('timer is done'); }, 1000); console.log( timer.complete ); // complete? false // check the timer object after it has expired setTimeout(function() { console.log( timer.complete ); // complete? true }, 1500); 

EDIT: Updated to make this consistent in strict mode and to support the optional argument passed to the callback. Thanks @Saxoier for the note.

+4
source

Yes, this is a condition using closure. This is pretty straight forward.

So that you do not call it again and again, as you say, you can try something like this ...

 // declare only once, singleton concept using closure (function() { var timerReference, timerMethod = function(fn) { fn(); if (timerReference) { window.clearTimeout(timerReference); } timerReference = window.setTimeout(function() { timerMethod(fn); }, 30000); }; window.doTimer = function(fn) { timerMethod(fn); }; })(); // you can call this as many times as you like doTimer(function() { alert('hi'); }); doTimer(function() { alert('hi again'); }); 

In this case, the call to doTimer () will destroy the previous one before it will always have only one timer.

I can also write code that will queue and wait for the last to complete, but this is another entry.

+1
source

Source: https://habr.com/ru/post/1390953/


All Articles