Asynchronous Javascript
Tags: javascript, codenewbie, 100daysofcode, functional
Published: 2021-02-07 14:53:30

Hello developers!!🤗🤗 In this article, we will study the asynchronous behavior of Javascript. 

> Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure, or progress. 

Before dive deep into the concepts, I recommend you go through the [callback Functions](https://dev.to/anuradha9712/callback-functions-in-javascript-215e) article in this series for a clear understanding of how **setTimeout** & **callback Functions** works.

In this article we will cover: 

- Call Stack
- Event Loop
- Callback Queues
- Visual Representation of Asynchronous Programming


## Call Stack

- Javascript is the synchronous single-threaded language, which means it has only one call stack and it can do only one thing at a time. 
- This call stack is present inside the JS engine & all the code of Javascript is executed inside this call stack. 

Let's look at the example:


```javascript
function myFunction(){
    console.log("inside function");
}

myFunction();
console.log('Program End');
``` 


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612600409833/IP-IbFP3r.png)

- Whenever we execute any JS code, a **Global Execution Context** is created and pushed inside the call stack.
- For any function, a separate Execution context is created and pushed into the call stack.
- Next, it executes the function `myFunction` and prints **inside function** in console.
- When function execution is complete, it is popped out of the call stack.
- Now it goes to the global execution context and prints **Program End** in the console.
- After all program execution context is completed, the global execution context is popped out of the stack. 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612601350170/jcSl2O29Q.png)

So the main job of this call stack is to execute whatever comes inside it.

But what if we want to run a specific script after 10 sec, or have some function B that needs to be executed only after function A completes its execution ??? But call stack does not have a timer. 

Here **Event Loop** & **CallBack Queue** came to our rescue. Let's see how things work behind the scene!!

## Asynchronous Javascript

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612700045799/eJ1aickia.png)

All these made asynchronous programming possible in Javascript. 

**Event Loop**

> The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, it will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a *tick* in the Event Loop. Each event is just a function callback.

Try to understand this concept using an example:


```javascript
console.log("start");

setTimeout(function callbackFn(){
    console.log("Callback Function");
},5000)

console.log("end");
``` 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612703948774/fdSLroO-w.png)

Let's try to examine the state of Call Stack, Callback Queue, Web APIs, & Console during the execution of the above code snippet.

- Initially, everything is empty.
- `console.log("start");` is added to the call stack.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612704455634/omP16H8no.png)

- `console.log("start");` is executed, and print `start` in the console.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612704681638/eHj52bb_o.png)

- `console.log("start");` is removed from the call stack


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612704812638/c7_BCYujP.png)

- `setTimeout(function callbackFn(){...})` is added to the call stack.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612705287889/-9oNJdH8r.png)

- `setTimeout(function callbackFn(){...})` is executed. The browser creates a timer as part of the Web APIs. It is going to handle the countdown for you. 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612705607452/ZBOusflNR.png)

- As it takes some time for the timer to expires but **Javascript waits for none** and remove the `setTimeout(function callbackFn(){...})` from the call stack and moves to the next line of code.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612705740195/dtQVbTqoR.png)

- `console.log("end");` is added to the call stack. 


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612705863903/G-bDVzsnx.png)

- `console.log("end");` is executed and prints `end` to the console. After that, it is removed from the call stack.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612706050261/NECecWhtN.png)

- When the timer expires after 5000 ms, our callback function `callbackFn` which is earlier attached to the Web APIs is pushed to the callback queue.  


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612706558834/3HnmGLrU9.png)

- Event loop continuously check if the call stack is empty and if it is empty then it takes the first event from the callback queue and pushes it to the call stack.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612706745725/-XowldPqh.png)

- `callbackFn` is executed and add `console.log("Callback Function");` to the call stack

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612706829962/c7gsroAQz.png)

- `console.log("Callback Function");` is executed and prints `Callback Function` in the console.


![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612707206049/VAMnw7qpa.png)

- `console.log("Callback Function");` is removed from the call stack.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612707293361/SYCVgg0EP.png)

- There is nothing more to execute in `callbackFn`, hence it is also removed from the call stack.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1612707397322/BxDHh9PUG.png)

## Summary

Let's have a quick recap of all the steps we perform in the above code snippet.

![Webp.net-gifmaker.gif](https://cdn.hashnode.com/res/hashnode/image/upload/v1612707785904/U32u4sUmS.gif)

## Wrap Up!!

Thank you for your time!! Let's connect to learn and grow together.

[LinkedIn](https://www.linkedin.com/in/anuradha-aggarwal-4a2751107/) [Twitter](https://twitter.com/Anuradh06359394)

[![Buy-me-a-coffee](https://cdn.buymeacoffee.com/buttons/v2/default-blue.png)](https://www.buymeacoffee.com/anuradha2612)