Is Javascript synchronous(blocking) or Asynchronous(nonblocking) by default

static void main picture static void main · May 13, 2013 · Viewed 16.5k times · Source

I am trying to grasp on Javascript Asynchronous functions and callbacks.

I got stuck on the concept of callback functions, where I am reading on some places: they are use to have sequential execution of code (mostly in context of jquery e.g animate)and some places specially in the context of Nodejs; they are use to have a parallel execution Asynchronous and avoid blocking of code.

So can some expert in this topic please shed light on this and clear this fuzz in my mind (examples??). so I could make my mind for the usage of callback function

or that is solely depends on the place of where you are calling/placing a callback function in your code? .

Thanks,

P.S: I am scared that this question would be close as subjective but still I could expect concrete answer for this (perhaps some examples)

Edit: actually this is the example from internet which makes me ambigous:

function do_a(){
  // simulate a time consuming function
  setTimeout( function(){
    console.log( '`do_a`: this takes longer than `do_b`' );
  }, 1000 );
}

function do_b(){
  console.log( '`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`' );
}

do_a();
do_b();

Result

`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`

when JS is sequential then do_b should always come after do_a according to my understanding.

Answer

Dancrumb picture Dancrumb · May 13, 2013

The core of JavaScript is largely synchronous, in that functions complete their task fully, before completing. Prior to the advent of AJAX, it was really only setTimeout and setInterval that provided asynchronous behavior.

However, it's easy to forget that event handlers are, effectively async code. Attaching a handler does not invoke the handler code and that code isn't executed until some unknowable time in the future.

Then came AJAX, with its calls to the server. These calls could be configured to be synchronous, but developers generally preferred async calls and used callback methods to implement them.

Then, we saw the proliferation of JS libraries and toolkits. These strove to homogenize different browsers' implementations of things and built on the callback approach to async code. You also started to see a lot more synchronous callbacks for things like array iteration or CSS query result handling.

Now, we are seeing Deferreds and Promises in the mix. These are objects that represent the value of a long running operation and provide an API for handling that value when it arrives.

NodeJS leans towards an async approach to many things; that much is true. However this is more a design decision on their part, rather than any inherent async nature of JS.