Praveen Gaur
5 min readFeb 18, 2019

Unthreading Asynchronous JS

If you are a JS developer, you must have heard the term Asynchronous execution, in fact most of you might have already used it in one way or the other.

But we are trying to identify the fundamental answers to:

Why we need Asynchronous behavior?

How exactly this works in browser, behind the scene?

What are the components involved: Event Loop, Task Queues, Execution Stack & Web API(s).

So, first thing first, let’s just understand the fundamental question why you need the Asynchronous behavior?

If you are coming from JAVA/C background, then you can understand the multi-threaded environments & the advantages: running multiple tasks in parallel, so that the main processing is not blocked.

The whole idea is to let some other thread handle the trivial task and the main(not the real main thread) thread continue to work on the more pressing affairs.

But, as you know JavaScript is a single threaded programming language i.e. we can not just spun off the new threads out of thin air(like in JAVA), then how to deligate/delay the trivial tasks, such that the more important tasks(to continue with the current important task) are executed on priority, at the same time ensuring that these trivial tasks will also be executed later on.

Note the important thing in the last line — “….executed later on”, not in parallel because that can’t be done(yes there are ways — will discuss that in other story), as JS is single-threaded. So, the only way of doing this is by delaying the execution of trivial tasks.

So, now we know that the phenomenon of delaying some of tasks is known as ASYNCHRONOUS EXECUTION. Delaying to running in parallel !!

Now, with that established theory out of the way. How would we actually do this? How to execute the code Asynchronously?

Some more theory(before we jump on to the code..) :)

By default the JS engine implementations(like Chrome’s V8 & Mozilla’s SpiderMonkey) do not support the asynchronous execution, then how the heck it works?? WebApi(s) is the super hero here, as the browsers got smarter — they have started coming up with their own code implementations to complement the execution engines, and such functionalities which are exposed by the browsers explicitly are called WebApi(s).

These WebApi(s) provide the support of asynchronous execution using the CALL BACK.

  1. Developer has to wrap the trivial code piece in a function, which needs to delayed for execution.
  2. Then pass this function created in step-1 as the first argument in setTimeout function. Now this function function becomes the callback function.(Call back functions could be executed synchronously as well but here we are concerned about asynchronous execution).
  3. setTimeOut function is the way to tell the execution engine that the execution of the given function(callback function) has to be delayed so that the main thread can continue to execute the rest of the code.
  4. When the rest of the code is done processing, then the callbacks are picked for execution.

Enough words, let’s do some code !!!

Suppose, you are creating an Ecommerce website & task is to create a PDP(Product detail page). On this page there are some trivial components like product image, price, description & also, there are some non-trivial(which can be delayed to execute the important components first) components like Customer reviews.

So, your JS code would look like this:

var createPDP = () => {// 1) creating the image PDP, pricing components:console.log(‘creating the image PDP, pricing components’);//2) creating the customer reviews components:console.log(‘creating the customer reviews components’);//3) creating the product description components:console.log(‘creating the product description components’);}createPDP();

If you execute the code above in the browser console, you would see something like:

Synchronous execution

This is the classic example of synchronous execution & the problem is: while the ‘2’ is being executed(reviews component), 3 is waiting & if 2 takes 5 MS to execute, for all those 5MS execution will be blocked and page will be half rendered.

Better approach is to defer point 2 to be executed later on — when 1 & 3 are done. That can be done using the asynchronous call back(s):

var createPDP = () => {// 1) creating the image PDP, pricing components:console.log('creating the image PDP, pricing components');//2) creating the customer reviews components://Doing the asynchronous way - using the call back. defering the execution by 1 second.setTimeout(()=>{console.log('creating the customer reviews components');}, 1000);//3) creating the product description components:console.log('creating the product description components');}
createPDP();

The result of the above code would be:

Result of asynchronous execution

Now compare the two responses side by side:

Synchronous VS Asynchronous execution.

Observe the outputs, using the asynchronous call backs, we have been able to defer the execution of the non-trivial task till the end, to the point where all the execution tasks are completed.

setTimeOut is function which is provided by the WebAPI(timer.js) which enables developers to run the tasks in asynchronous way.

Key points to remember about setTimeOut:

  1. It takes 2 arguments, 1st argument is the call back(task) that you want to execute asynchronously. Second argument is the time for which you need to delay the execution.
  2. The time that we provide is the minimum time for which the execution is delayed but not maximum. This functionality guarantees the minimum delay as the specified time but it is not guaranteed that the task will be executed just after the time is over, it may or may not — it depends.
  3. All the asynchronous tasks are queued as they are triggered & are executed in the same order as they were triggered. Hence the 2nd point, tasks will be delayed by the specified time for sure but will be executed after all other tasks which were queued before this one.
  4. This order is maintained in a queue called ‘Task Queue’.

I hope, this post was helpful in understanding the asynchronous behavior. In the upcoming series, i will touch upon:

How the asynchronous behaviour works, behind the scenes. Event loop, task queue & execution stack. Also, will discuss the Promises, Asyc/Await and other concepts.