Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can clearTimeout remove an unprocessed callback of a fired timeout event in Javascript?

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

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

Informally speaking, my guess is that once the timeout fires, it queues up the callback and destroys itself – making a clearTimeout with that timer's id have no effect on the queued up callback.

like image 811
mrjoelkemp Avatar asked Aug 28 '12 18:08

mrjoelkemp


1 Answers

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

edit — for completeness, the test I constructed was 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 that script block is finished, and they should run in the order they were requested. Thus, "t1" should clear "t2" before the browser runs its callback. Because no alert() happens, I concluded that the clearTimeout() call "worked" in that it prevented the second callback from running even though it's timer had already expired.

Exactly how things work in the browser(s) is not something I'm familiar with, so there could be some situation where the clearTimeout() doesn't have the same effect. It seems pretty non-deterministic anyway, given the execution model.

like image 124
Pointy Avatar answered Oct 19 '22 06:10

Pointy