DEV Community

Cover image for Async Javascript & how it works👩‍💻
Aishanii
Aishanii

Posted on

Async Javascript & how it works👩‍💻

As we discussed earlier, javascript is a single-threaded, synchronous language. But a lot of time we observe async javascript in different courses and modules, which kind of invalidates the above statement. Let's try to understand this.

We know javascript has a call stack which has the global execution context. When a function in executed, a new execution context is pushed to stack and popped once the function has returned.

Now there are a lot of functions made available by browser which take time and if pushed to stack can block it, also known as blocking the main thread. These functions, hence, were made asynchronous. Look at this example with setTimeout:

console.log("hello, let's go!")

setTimeout(()=>{
    console.log("We are back for a quest.")
},7000)

function greet(){
    console.log("Adventure time...")
}

greet();
Enter fullscreen mode Exit fullscreen mode

Image description
The callback arrow function in setTimeout is shown in console after 7000ms. Let's take a look how does this happen.

Behind the scenes of Async Javascript:

Image description

We'll work around this figure and understand the whole thing.

  • Initially, there is the global execution context pushed into the call stack and the console.log("hello, let's go!") is executed.

  • Once we reach setTimeout() (Web API, not a part of JS), the timer provided by browser is set to 7000ms (as in the code) and is not executed.

The callback function is pushed to the task queue once the timer goes off.

  • Now, it moves forward and encounters function greet(). Functional programming is the strongest suite of JS and hence a new execution context is created and pushed in the call stack.

  • Once the function is executed and the end of script is reached, global execution context is popped
    Image description

The event loop's purpose is to check whether the call stack is empty or not. As soon as the stack is empty (& only when it is empty) and the timer has gone up, it removes callback function from the queue and pushes it in the call stack for execution.

The callback function just sits in the web APIs environment until timer goes off.

there is also multitask queue that basically handles functions with higher priority, involving promises and change in the DOM tree.
🌟Using microtasks in JS by MDN Docs
🌟Asyn Javascript by James Q

Top comments (1)

Collapse
 
aishanipach profile image
Aishanii

Feel free to correct or add anything via comments if you know more!