views:

573

answers:

2

I have been under the impression for that JavaScript was always asynchronous. However, I have learned that there are situations where it is not (ie DOM manipulations). Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous? Does jQuery affect this at all?

+6  A: 

JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.

Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that you don't know exactly when they might happen.

I would recommend you to give a look to the following article:

That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.

async

CMS
+13  A: 

Javascript is always synchronous and single-threaded meaning if you're executing a Javascript block of code on a page then no other Javascript on that page will currently be executed.

Javascript is only asynchronous in the sense that it can make, for example, AJAX calls. The code will stop executing until the call returns (successfully or in error), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's running.

This same kind of callback operates with Javascript timers.

Describing Javascript as asynchronous is perhaps misleading. Iti's more accurate to say that Javascript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on AJAX calls to make them synchronously (with the async: false option). It's a beginner error to be tempted to use this as it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this will block all Javascript on the page until it finishes, included all event handlers and timers.

cletus