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!
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.
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").
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With