How are event handlers in JavaScript handled by an event loop?

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

Say I have two event handlers attached to buttons A and B. Both event handlers execute the same time to complete. If I first press the "A" and "B" buttons, is it true that the event handler for the "A" button is always executed first (since the event loop is a FIFO queue), but when they end is completely unpredictable? If so, what actually determines this order?

+2
source share
3 answers

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

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

The execution order is simple and JavaScript in the browser is single-threaded the most of that time, and in practice you do not need to worry about the order of things.

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

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

Regardless of whether order DOM events are logged, this is not part of JavaScript, but part of this API. More specifically, it is defined right here . So, to your question: Yes, the order of the event execution is defined, with the exception of control keys (for example, (control alt delete)), which can hang the evaluation order up.

+3
source

Javascript engine is single threaded. All event handlers occur sequentially; the click handler for A will be called and terminated before the handler for B starts. You can see this in sleep() ing in one handler and make sure that the second handler does not start until the first is completed.

Note that setTimeout not valid for this test because it essentially registers a function with a motor return at a later time. setTimeout returns immediately.

This scenario should demonstrate this behavior.

+2
source

Well, the commands really are in FIFO when javascript is executed. However, handlers can spend different periods of time to send the result. In this case, the response from handler B may come back earlier, and the response from handler A may come later.

-1
source

Source: https://habr.com/ru/post/953937/


All Articles