gpt4 book ai didi

JavaScript 事件循环 : Different queue for different types of events?

转载 作者:行者123 更新时间:2023-11-30 13:50:18 26 4
gpt4 key购买 nike

摘自《Javascript 忍者的 secret 》一书:

EVENTS ARE ASYNCHRONOUS

Events, when they happen, can occur at unpredictable times and in an unpredictable order (it’s tricky to force users to press keys or click in some particular order). We say that the handling of events, and therefore the invocation of their handling functions, is asynchronous.

The following types of events can occur, among others:

■ Browser events, such as when a page is finished loading or when it’s to be unloaded

■ Network events, such as responses coming from the server (Ajax events, serverside events)

■ User events, such as mouse clicks, mouse moves, and key presses

■ Timer events, such as when a timeout expires or an interval fires

上述所有事件是否都由事件循环中的同一个队列处理?我在尝试在脚本中测试 DOM 单击事件时遇到了这个疑问:

<html>

<body>
<button id="bId">A button</button>

</body>
<script>
function testing() {
document.getElementById('bId').addEventListener("click", function () {
console.log('clicked');
})
console.log('before click');
document.getElementById('bId').click();
console.log('after click')
};
testing();
</script>

</html>

据我了解,任何使用事件循环队列的异步事件(如计时器、 promise )都将等待调用堆栈为空。

在上面的代码中,如果 DOM 事件正在使用事件循环队列,则输出不应该是 clicked。在 before click 之后打印和 after click console.log()函数调用?

不同类型的事件是否有不同类型的队列?

最佳答案

我认为这可能有帮助,但它也按照直接调用的点击顺序打印,看起来它们是一样的。

这是 mdn 必须说的:

在指定的 EventTarget 处调度一个事件,(同步)以适当的顺序调用受影响的 EventListener。正常的事件处理规则(包括捕获和可选的冒泡阶段)也适用于使用 dispatchEvent() 手动调度的事件。

但我很确定当用户实际点击元素时情况并非如此。

<html>

<body>
<button id="bId">A button</button>

</body>
<script>
function testing() {
document.getElementById('bId').addEventListener("click", function () {
console.log('clicked');
})
console.log('before click');

var el = document.getElementById('bId');
var event;
if (window.CustomEvent) {
event = new CustomEvent('click');
} else {
event = document.createEvent('click');
event.initCustomEvent('click', true, true);
}
el.dispatchEvent(event);
console.log('after click')
};
testing();
</script>

</html>

关于JavaScript 事件循环 : Different queue for different types of events?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390772/

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