Can clearTimeout remove an unprocessed callback of

2020-08-24 02:13发布

问题:

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.

回答1:

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.