Alex Rivera | Logout

Are event handlers guaranteed to complete before AJAX callbacks are invoked?

Asked 2012-04-03T18:19:47.693
11

Suppose I have a event handler which makes two AJAX calls to the server:

$("#foo").click(function(){ 
    $.get("bar", function(){ alert("Hello"); });
    $.get("baz", function(){ alert("World"); });
});

I realize that the order in which the callbacks are invoked is nondeterministic, since it depends on how long each request takes, etc.

But here's my question: is it guaranteed that I'll reach the end of my event handler before either of the callback functions are invoked? I've read that all Javascript for a page executes in a single thread, so I think that implies that my click event handler is guaranteed to complete before any of the callbacks can be invoked.

Is this correct? Or is it possible that the first request might be complete AND the first callback executed before we even get to the end of our event handler?

Edit
Report

1 Answer

11

Yes, this is guaranteed and you are right - there is just a single thread (ignoring s for the moment). When a piece of JavaScript code executes (occupies the execution thread) and an AJAX callback arrives (or any other GUI event, timeout, etc.) it is queued and waits until the execution thread is free (current piece of code finishes).

JavaScript engine will never interrupt running code to handle incoming event - events will always gently wait in a queue. This is the reason why the GUI appears to be freezing when CPU-intensive code is executing - no events are handled. Also this is why synchronous AJAX requests are bad.

See also

answered 2012-04-03T18:22:32.580

Your Answer