The behavior of Asynchronous Javascript under the hood

JavaScript Meme from the show Game of Thrones

Oh well! It did take me a while to wrap my head around how Javascript, being a single-threaded language (meaning it has only one execution path), handles asynchronous calls. Asynchronous Behaviour is possible through Callback Queue! I will be explaining this in a bit.

picture of 4 boxes labeled call stack, callback queue, web API and code

In the above diagram, we have, Function printHello, which should print Hello; and three more console logs which should print numbers one, two, and three. The order in which these will print are as followed:

  • Console.log(“1”) will go to the call stack and then will immediately pop off
  • Console.log (“2”) will go to the call stack and then will immediately pop off
  • Console.log(“3”) will go to the call stack and then will immediately pop
  • printHello function will go to the call stack for a split second and then immediately move to web API, since we have a setTimeout web API call. After it has been executed there, it will go to the callback queue and wait there, until all synchronous calls have been executed.
  • Remember all these are happening in a parallel manner.
// print 1
// print 2
// print 3
// "hello world"

Javascript runs inside a browser, it does not run in a vacuum. setTime outs, DOM, Network calls, sockets; all these features are provided by the browser. Callback Queue makes the whole Asynchronous behavior possible. Synchronous Javascript will be placed on call stack so, therefore, print hello (without the setTimeout) along with the console logs will be on the Call Stack. But when it comes to setTimeout which is a web browser API call, it will go to the Web Browser API, and run there.

While the setTimeout is in the web API, the other console logs will still run in the Call Stack and the setTimeout will wait in the Callback Queue:

  • When all the synchronous actions have been executed, and the Call Stack is empty, Callback queue will then pass the setTimeout action to the call stack
  • In order to utilize asynchronous calls, we need to make use of Browser API
  • A very strict rule is, in order for an asynchronous function to be executed, it must go through Web API and then call-back queue. When the Synchronous codes are executed, the Callback queue will pass its code to the call stack.

I hope it made sense to you! On my next blog, I will describe how “promise” and “ call back functions” in Javascript behaves and it’s asynchronous nature.

Happy Learning!

Coach @FlatironSchool

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store