Difference Between Synchronous and Asynchronous in Ajax

By default, the $.ajax request in jQuery is set to asynchronous. The variable name is async and the value is set to true. This gave me a little confusion as well when first learning about it, so let’s go over it.

Asynchronous vs. Synchronous

The default setting in jQuery. In my experience, Asynchronous should almost always do the trick. There are also 2 situations in particular which don’t even allow for a synchronous call.

  • Cross domain requests. If I am doing an ajax request from techjunkie.com to a file on whereever.com(a completely different domain), that would be a cross domain request.
  • jsonp – If you are looking to retrieve JSON data cross-domain, JSONP is what you’re looking for.

When to use Synchronous

You should first be aware that setting async to false freezes your browser. It locks it, completely. Not just your page, but every page that the user may have open. For example, if your server slows down mid-request, you have effectively disabled their browser until your server has a chance to catch up and pass along the needed data.

Instead of risking it with a synchronous call, just specify a callback function on success or error. You get to the same endpoint without possibly ruining the user’s browsing experience. In short, don’t use a synchronous call. Its bad for your application and UX.

Posted by Will on May 24, 2012

Leave a Reply

Your email address will not be published. Required fields are marked *

TechJunkie Also Recommends