Andrei Hrabouski
Andrei Hrabouski

Reputation: 125

JS browser event handling

Right now I've got a little bit confused with browser events. I'm still not sure how event loop starts working. For example, when I dispatch custom event in the mid of some function, does event handling start right away or is it moved to the event queue? And what about other events? If I click or the page is loaded, what happens? When does the event handling process begin?

Upvotes: 1

Views: 197

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

I'm still not sure how event loop starts working.

Typically in browsers it starts working as soon as you enter a page and stops working when you exit it.

For example, when I dispatch custom event in the mid of some function, does event handling start right away or is it moved to the event queue?

There are synchronous events (that fire right away) and asynchronous events that fire in the next iteration. Your code will generally run to the end of its execution before anything else is run unless you explicitly terminate it.

DOM custom events are typically synchronous. That is - you're the one triggering them and it happens right away.

For example if you have code running and a "click" event happens or a timer set with setTimeout is fired your code will finish running first - nothing "interrupts" your code.

When does the event handling process begin?

As specified:

Events may be dispatched either synchronously or asynchronously.

Events which are synchronous (sync events) must be treated as if they are in a virtual queue in a first-in-first-out model, ordered by sequence of temporal occurrence with respect to other events, to changes in the DOM, and to user interaction. Each event in this virtual queue must be delayed until the previous event has completed its propagation behavior, or been canceled. Some sync events are driven by a specific device or process, such as mouse button events. These events are governed by the event order algorithms defined for that set of events, and a user agent must dispatch these events in the defined order.

Upvotes: 1

Related Questions