7

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!

9
  • 1
    Just wait a little longer. Commented Dec 15, 2014 at 12:25
  • isn't the line "$(b).trigger("event")" needs ";"? Commented Dec 15, 2014 at 12:25
  • 2
    @NaeemShaikh Yes, it does. Just because it sometimes inserts it for you, doesn't mean it's okay to drop it. Commented Dec 15, 2014 at 12:30
  • 1
    @JLRishe That's not just jQuery, it reproduces with plain DOM events. Commented Dec 15, 2014 at 12:33
  • 1
    @SecondRikudo: strictly speaking, line-ending ; characters are optional (from the point of view of the author, not the the interpreter). It just leads to horrible, horrible problems when they're automagically inserted by the interpreter (which often inserts them in unexpected, or unanticipated, places). Commented Dec 15, 2014 at 12:34

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, I'm genuinely not trying to be a nuisance; I'll stop now :-/
You really don't have to stop - I'm all for improving answers and your help is appreciated. In fact I don't think people do that enough around here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.