How do event handlers in JavaScript get processed by the event loop?

前端 未结 3 1494
心在旅途
心在旅途 2021-01-01 07:44

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

Let\'s say I have two event handlers attached to buttons A and B. Both event handlers take ex

相关标签:
3条回答
  • 2021-01-01 07:50

    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).

    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.

    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.

    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.

    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.

    0 讨论(0)
  • 2021-01-01 08:01

    Well the commands are indeed in a FIFO when executed by javascript. However, the handlers may take different amounts of time to send you the result. In this case the response from handler B may come back earlier and response from handler A may come later.

    0 讨论(0)
  • 2021-01-01 08:09

    The Javascript engine is single threaded. All of your event handlers happen sequentially; the click handler for A will be called, and finish before the handler for B ever starts. You can see this by sleep()ing in one handler, and verifying that the second handler will not start until the first has finished.

    Note that setTimeout is not valid for this test, because it essentially registers a function with the engine to be called back at a later time. setTimeout returns immediately.

    This fiddle should demonstrate this behavior.

    0 讨论(0)
提交回复
热议问题