Can clearTimeout remove an unhandled event callback with timeout disabled in Javascript?

If I call clearTimeout on a setTimeout event that has already been fired, but whose callback is still in the execution queue, will clearTimeout prevent this event from being processed?

In other words, is it still possible to clear the timeout event during the delay of the timer and its callback?

Speaking informally, I assume that as soon as the timeout fires, it pauses the callback and destroys itself - creating a clearTimeout with this timer id does not affect the callback in the queue.

+7
source share
1 answer

I think the answer is yes . (I am using Firefox at the moment.)

edit - for completeness, I constructed this:

 var t1 = setTimeout(function() { clearTimeout(t2); }, 0); var t2 = setTimeout(function() { alert("hello world"); }, 0); 

The idea is that both timers should become "ready" immediately after the script block is completed, and they should be started in the order in which they were requested. Thus, “t1” must clear “t2” before the browser makes a callback. Since there is no alert() , I came to the conclusion that the clearTimeout() call "worked" in that it prevented the second callback from starting even though the timer had already expired.

Exactly how everything works in the browser (s), I am not familiar with the fact that there may be a situation where clearTimeout() does not have the same effect. In any case, this seems rather non-deterministic, given the execution model.

+5
source

All Articles