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

。_饼干妹妹 提交于 2020-01-02 02:22:08

问题


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.



来源:https://stackoverflow.com/questions/12165145/can-cleartimeout-remove-an-unprocessed-callback-of-a-fired-timeout-event-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!