简体   繁体   中英

JavaScript event loop : Different queue for different types of events?

Excerpt from the book "Secrets of a Javascript Ninja":

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

Are all these above events handled by same queue in the event loop? I got this doubt while trying to test a DOM click event in a script:

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

As i understand, any asynchronous events (like timer, promises) using the event loop queue will wait for call stack to be empty.

In the above code if the DOM events were using the event loop queue shouldn't the output clicked be printed after the before click and after click console.log() function calls?

Are there separate types of queues for different kinds of events?

I thought this might help, but it also prints in the order of click called directly, it looks they are same.

This is what mdn has to say:

Dispatches an Event at the specified EventTarget, (synchronously) invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

But I am pretty sure this is not the case when the element is physically clicked by the user.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM