JavaScript中的事件处理程序如何被事件循环处理? [英] How do event handlers in JavaScript get processed by the event loop?

查看:78
本文介绍了JavaScript中的事件处理程序如何被事件循环处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对浏览器如何处理JavaScript事件感到有些困惑。

I'm a little bit confused about how browsers handle JavaScript events.

假设我有两个事件处理程序附加到按钮A和B.两个事件处理程序都采用完全相同的时间完成。如果我先单击按钮A然后单击按钮B,那么按钮A的事件处理程序是否始终首先执行(因为事件循环是FIFO队列),但是当它们完成是完全不可预测的?如果是这样,实际上是什么决定了这个订单?

Let's say I have two event handlers attached to buttons A and B. Both event handlers take exactly the same time to complete. If I click on button A first and button B next, is it true that the event handler for the button A is always executed first (because the event loop is a FIFO queue), but when they finish is completely unpredictable? If so, what actually determines this order?

推荐答案

。执行事件处理程序的顺序是有保证的,实际上它们不会重叠。

Yes. The order of event handlers executed is guaranteed, and in practice they will not overlap.

这是事件循环作为并发模型的美妙之处。您不必考虑线程问题,例如死锁,活锁和竞争条件 大多数时间 (虽然并非总是如此)。

This is the beauty of the event loop as a concurrency model. You don't have to think about threading issues like deadlocks, livelocks and race conditions most of the time (though not always).

执行顺序很简单,浏览器中的JavaScript是单线程 大多数 ,在实践中你不必担心事情的执行顺序。

Order of execution is simple and JavaScript in the browser is single threaded most of the time and in practice you do not have to worry about order of execution of things.

然而保证鼠标事件的事实顺序几乎与JavaScript无关。这不是JavaScript语言的一部分,而是称为 DOM API 的一部分,DOM(文档对象模型)是JavaScript与浏览器和您编写的HTML交互的方式。

However the fact order of mouse events is guaranteed has hardly anything has to do with JavaScript. This is not a part of the JavaScript language but a part of something called the DOM API, the DOM (document object model) is how JavaScript interacts with your browser and the HTML you write.

称为主机对象的东西在JavaScript规范中定义为浏览器中的外部对象JS,并且在这种情况下指定了它们的行为在DOM API中。

Things called Host Objects are defined in the JavaScript specification as external objects JS in the browser works with, and their behavior in this case is specified in the DOM API.

无论订单是否已注册订单DOM事件都不是JavaScript的一部分,而是该API的一部分。更具体地说,就在这里。所以对你的问题:是的,事件执行的顺序是确定的,除了控制键(如(控制alt删除)),这可能会导致评估顺序混乱。

Whether or not the order DOM events are registered is guaranteed is not a part of JavaScript but a part of that API. More specifically, it is defined right here. So to your question: Yes, order of event execution is certain except for control keys (like (control alt delete)) which can mess order of evaluation up.

这篇关于JavaScript中的事件处理程序如何被事件循环处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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