clearTimeout可以在Javascript中删除已触发的超时事件的未处理回调吗? [英] Can clearTimeout remove an unprocessed callback of a fired timeout event in Javascript?

查看:201
本文介绍了clearTimeout可以在Javascript中删除已触发的超时事件的未处理回调吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我为 setTimeout 调用 clearTimeout 已经触发但其回调仍在执行队列中的事件, clearTimeout 是否仍会阻止该事件被处理?

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?

非正式地说,我的猜测是,一旦超时触发,它会排队回调并销毁本身 - 使用该计时器的id生成 clearTimeout 对排队的回调没有影响。

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.

推荐答案

我认为答案是。 (我现在正在使用Firefox。)

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);

这个想法是两个计时器应该在脚本块完成后立即准备好,并且它们是应该按照他们的要求运行。因此,t1应在浏览器运行其回调之前清除t2。因为没有发生 alert(),我得出结论, clearTimeout()调用工作,因为它阻止了第二次即使它的计时器已经过期,也可以从运行中回调。

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.

浏览器中的工作原理并不是我熟悉的,所以可能会有一些 clearTimeout()的情况不同。考虑到执行模型,无论如何它似乎都是非确定性的。

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.

这篇关于clearTimeout可以在Javascript中删除已触发的超时事件的未处理回调吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆