简体   繁体   English

事件处理程序中的setTimeout似乎不触发

[英]setTimeout from within an event handler not appearing to fire

Am aware that not all setTimout tasks put on the queue are actually fired (thanks a post by bobnice on this). 我知道并不是所有放入队列的setTimout任务实际上都被触发(感谢bobnice对此发表的评论)。 Yet I can't understand why it would not be reached in this case : 但是我不明白为什么在这种情况下无法实现:

I add the following event handler to an anchor link (via addEventListener( 'click', ... ) to experiment with so-called "in-flight event modification" : 我将以下事件处理程序添加到锚定链接中(通过addEventListener( 'click', ... )来尝试所谓的“进行中事件修改”:

var f = function(e) {  
    e.preventDefault(); 
    e.stopPropagation(); // capture first event
    e2 = new MouseEvent("click",{metaKey:true}); // create second event where we hold meta
    e.target.removeEventListener('click', f, false); // remove this handler so no stackoverflow
    e.target.dispatchEvent(e2); // dispatch second event, a "modified" first event.
};

Works fine. 工作正常。

However, an earlier version had this : 但是,较早的版本具有:

setTimeout( 0, function () {
    e.target.dispatchEvent(e2); // dispatch second event, a "modified" first event.
});

From within the handler (as a debugging patch to try to avoid stackoverflow when I couldn't get the removeEventListener to work -- I had neglected to assign my function f to a variable). 从处理程序内部(作为调试修补程序,当我无法使removeEventListener正常工作时,它试图避免堆栈溢出-我忽略了将函数f分配给变量)。

Why would this setTimeout not execute? 为什么此setTimeout无法执行? In my handful of tests, it never once executed the dispatching of the second event from within the listener for the first event. 在我的少数测试中,它从未执行过从监听器内部为第一个事件调度第二个事件的过程。

Clearly, the setTimeout puts the execution context of dispatchEvent outside of the stack frame for the function f , as f returns before dispatchEvent fires. 显然,setTimeout将函数fdispatchEvent的执行上下文放在函数f的堆栈框架之外,因为fdispatchEvent触发之前返回。

Or, rather, doesn't fire. 或者, 触发。

I would like to understand exactly why it didn't fire in this previous version of the code. 我想确切地理解为什么它在以前的代码版本中没有触发。

The timeout delay for setTimeout should be the second argument, not the first! setTimeout的超时延迟应该是第二个参数,而不是第一个! That's why it didn't fire. 这就是为什么它没有发射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM