最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Can clearTimeout remove an unprocessed callback of a fired timeout event in JavaScript? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Feb 9, 2023 at 20:13 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 28, 2012 at 18:16 mrjoelkempmrjoelkemp 4411 gold badge6 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

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

edit — for pleteness, 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 bee "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)

  1. 暂无评论