Aljoša Srebotnjak
Aljoša Srebotnjak

Reputation: 1331

event loop model in 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!

Upvotes: 7

Views: 106

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

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.

Upvotes: 3

Related Questions