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

后端 未结 1 674
礼貌的吻别
礼貌的吻别 2021-02-20 02:48

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

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-20 03:16

    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.

    0 讨论(0)
提交回复
热议问题