Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Events Handlers in JavaScript for one event fired as FIFO, LIFO or in parallel?

Does Events Handlers in JavaScript for one event fired as FIFO, LIFO or in parallel?

like image 836
Itay Moav -Malimovka Avatar asked Dec 17 '25 00:12

Itay Moav -Malimovka


2 Answers

It's very simple. DOM Level 2 Events module does not specify order in which event listeners are to be fired. However, DOM Level 3 Events module does specify order to be the same as registration one.

First registered — first fired.

Note that DOM Level 3 Events module is still a draft, whereas Level 2 one is a recommendation. Nevertheless, modern browsers often follow semantics of exactly this draft Level 3 specification, instead of an older Level 2 one.

In practice, IIRC, only IE doesn't respect order of event listeners. All other browsers implement it as FIFO (and as described in DOM L3 Events). You can also find related tests online :)

like image 54
kangax Avatar answered Dec 19 '25 14:12

kangax


Due the single threaded nature of JavaScript, events and timers are queued up and executed sequentially one at time, they run when there's been an opening in the execution.

This is best demonstrated with a diagram:

Events and Timers

After the first block finishes its execution, there are two asynchronous events waiting, the Mouse Click Callback and the Timer, the browser picks the Mouse Click in this example, and the timer will wait until the next possible time, in order to execute.

Check this really good article about Timers and Events by John Resig.

like image 33
Christian C. Salvadó Avatar answered Dec 19 '25 12:12

Christian C. Salvadó



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!