Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous or Synchronous calling of event handlers in javascript

Tags:

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

like image 684
Sachin Avatar asked Apr 10 '13 11:04

Sachin


People also ask

Are event handlers synchronous?

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

Are event handlers asynchronous JavaScript?

JavaScript IS asynchronous... it will continue to process code, even if a method you called hasn't returned yet... so yes, that is correct. That is the very definition of async: NOT synchronized...

What are synchronous and asynchronous calls in JavaScript?

In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.

Are events in JavaScript synchronous or asynchronous?

Since JavaScript is a single-threaded programming language with a synchronous execution model that processes one operation after another, it can only process one statement at a time.


2 Answers

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

like image 71
freakish Avatar answered Sep 28 '22 04:09

freakish


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

like image 21
Dimitris Zorbas Avatar answered Sep 28 '22 05:09

Dimitris Zorbas