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 ?
zmag
8,28112 gold badges40 silver badges47 bronze badges
asked Apr 10, 2013 at 11:02
Sachin Jain
21.9k34 gold badges113 silver badges177 bronze badges
-
2all events are synchronous. You might also like to a look into event propagation quirksmode.org/js/events_order.htmlEjaz– Ejaz2013年04月10日 11:06:11 +00:00Commented Apr 10, 2013 at 11:06
2 Answers 2
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
xianshenglu
what do you think about the
Some event handlers are executed synchonously and others asynchronously.?freakish
@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.Some event handlers are executed synchonously and others asynchronously. See DOM-Level-3-Events
answered Jul 1, 2013 at 15:56
Dimitris Zorbas
5,4903 gold badges30 silver badges33 bronze badges
1 Comment
Charles Harris
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.
Explore related questions
See similar questions with these tags.
lang-js