22

Are event handlers executed synchronously or asynchronously in JavaScript? Here is JS bin which is showing that event handler is executed synchronously.

Code:

$('#toclick').bind('custom', function() {
    for (var i=0; i<100000; i++) {}
    console.log('Inside click handler');
});

$('#toclick').trigger('custom');
console.log('Outside click handler');

Output:

Inside click handler
Outside click handler

This means if we trigger an event, the code below it won't be executed unless all the event handlers are executed. Am I right ?

Bin with multiple event handlers

zmag
  • 7,825
  • 12
  • 32
  • 42
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 2
    all events are synchronous. You might also like to a look into event propagation http://www.quirksmode.org/js/events_order.html – Ejaz Apr 10 '13 at 11:06

2 Answers2

21

That's correct. All event handlers are fired synchronously and in order of binding.

BobRodes
  • 5,990
  • 2
  • 24
  • 26
freakish
  • 54,167
  • 9
  • 132
  • 169
  • Thanks freakish! Just got confused. Thanks for clarification. – Sachin Jain Apr 10 '13 at 12:23
  • 1
    what do you think about the `Some event handlers are executed synchonously and others asynchronously.`? – xianshenglu Jun 10 '18 at 10:29
  • 3
    @xianshenglu there's a confusion. Once an event is triggered all handlers bound to it run synchronously. But events (e.g. load) can be triggered asynchronously. So handlers are always synchronous. While events themselves need not. Note that `trigger` function triggers an event synchronously. – freakish Jun 10 '18 at 10:34
11

Some event handlers are executed synchonously and others asynchronously. See DOM-Level-3-Events

Dimitris Zorbas
  • 5,187
  • 3
  • 27
  • 33
  • 3
    Thanks for the useful information. On a side note, link only answers are discouraged. Please try to put more information in the answer. Thanks anyways!! – Sachin Jain Mar 01 '14 at 06:47