gpt4 book ai didi

javascript - 事件处理程序、事件队列和异步行为

转载 作者:行者123 更新时间:2023-12-03 13:52:59 26 4
gpt4 key购买 nike

考虑以下 React 组件。我的查询不限于React。这是一个 Javascript 问题:

function MyTest(){
const result = () =>{
console.log("Time to play");
setTimeout (() =>{
console.log("async")
},500);
};
useEffect(()=>{
document.getElementById('id-1').click();
console.log("When?");
})
return (
<button id="id-1" onClick={result}>Click me</button>
)
}

上述代码的输出为:

Time to play
When?
async

但我对事件处理程序感到困惑。我所知道的是:浏览器事件处理程序的行为与其他异步通知类似。它们是在事件发生时安排的,但必须等待正在运行的其他脚本完成才能有机会运行。如果上述正确,我期望以下输出:

When?
Time to play
async

因为执行堆栈不为空(console.log("When?") 位于其中),以便运行事件处理程序。上述三段论有什么问题?

附注为了让上面的内容更令人困惑,请查看 Asynchronous or Synchronous calling of event handlers in javascript

最佳答案

查看此链接 https://w3c.github.io/uievents/#sync-async

我看到这个:

Events may be dispatched either synchronously or asynchronously.

Events which are synchronous (sync events) are treated as if they are in a virtual queue in a first-in-first-out model, ordered by sequence of temporal occurrence with respect to other events, to changes in the DOM, and to user interaction. Each event in this virtual queue is delayed until the previous event has completed its propagation behavior, or been canceled. Some sync events are driven by a specific device or process, such as mouse button events. These events are governed by the event order algorithms defined for that set of events, and user agents will dispatch these events in the defined order.

所以我想这个假设并不总是如此:

browser event handlers behave like other asynchronous notifications.

并解释了为什么您会看到您所做的输出。

关于javascript - 事件处理程序、事件队列和异步行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59612826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com