Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event loop model in javascript

Tags:

javascript

based on: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop

stack frame is empty before next event is processed. So why in folowing snippet alert displays 1 instead of 0 because alert function should run before callback

var a=0;
var b={};

$(b).on("event", function (){
  a++;
});

$(b).trigger("event");
alert(a);

http://jsfiddle.net/nxjhokL0/

Thanks!

like image 519
Aljoša Srebotnjak Avatar asked Dec 15 '14 12:12

Aljoša Srebotnjak


People also ask

What is event loop model in NodeJS?

Event loop is an endless loop, which waits for tasks, executes them and then sleeps until it receives more tasks. The event loop executes tasks from the event queue only when the call stack is empty i.e. there is no ongoing task. The event loop allows us to use callbacks and promises.

What is event loop mechanism?

The event loop works by making a request to some internal or external "event provider" (that generally blocks the request until an event has arrived), then calls the relevant event handler ("dispatches the event").

What is event loop in JavaScript interview questions?

The event loop is a mechanism that allows JavaScript to perform non-blocking operations. When an asynchronous task is started, the event loop will start running. Once the task is completed, the event loop will again check for any other tasks that need to be performed.


1 Answers

Let's ignore the fact you have jQuery events here and not native DOM events since this reproduces with native DOM Events as dystroy has shown in his comment to the question.

Simply put MDN is misleading here. In general that article could use technical review.

If we check the DOM Events specification itself:

Events may be dispatched either synchronously or asynchronously.

"stack frame is empty before next event is processed. " is incorrect in the general case. It only happens with asynchronous events.

like image 64
Benjamin Gruenbaum Avatar answered Oct 19 '22 02:10

Benjamin Gruenbaum