24

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

1
  • 2
    all events are synchronous. You might also like to a look into event propagation quirksmode.org/js/events_order.html Commented Apr 10, 2013 at 11:06

2 Answers 2

23

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

Sign up to request clarification or add additional context in comments.

2 Comments

what do you think about the Some event handlers are executed synchonously and others asynchronously.?
@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.
11

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

1 Comment

The document outlines the events are fired either synchronously or asynchronously, but it doesn't specify whether the handlers themselves are executed synchronously. In my experience, once the event is dispatched, the handlers are executed synchronously in order of DOM binding, as specified above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.