Understanding Javascript’s Event Loop, Task Queue, and Microtask Queue: Mastering advanced Javascript

Vamsi Krishna Kodimela
Angular Simplified

--

Javascript is, by nature, single-threaded. How does it handle promises and asynchronous methods? How does it even execute them in parallel? The answer may not be straightforward. Let’s explore Javascript Asynchronous Programming…

Well-crafted and well-executed Architecture

Javascript has a well-crafted and well-executed architecture that combines the event loop, task queue, and microtask queue to make single-threaded language perform asynchronous operations.

Let’s take an example…

// Method-1
console.log("A");

// Method-2
setTimeout(()=>{
console.log("B");
},100);

// Method-3
setTimeout(()=>{
console.log("C");
},0);

// Method-4
console.log("D");

/***
*
* Output:
* ADCB
*
***/
  • Whenever execution starts, each method call will enter the CallStack for execution.
  • Methods that can give immediate results (Synchronous Methods)will be executed. Callbacks from Asynchronous methods will be handed over to their respective Web APIs.
  • Methods 1 and 4 will return immediately, and Methods 2 and 3 will be handed over to the setTimeout API to push it to the TaskQueue when the time comes.
  • Method 3 will be pushed to the Task Queue as the timer is 0, followed by Method 4 once the timer reaches 100.
  • Then, once it is free, each method in the Task Queue is moved to the call stack for execution. This is how Javascript processes asynchronous methods.

What is MicroTask Queue doing…?

  • MicroTask Queue is a dedicated queue that handles callbacks from Promises.
  • The callbacks in the MicroTask Queue will have high priority over the Task Queue, which means tasks from the Task Queue will only be moved to the Call Stack after all the tasks from the MicroTask Queue are moved to the Call Stack, no matter at what time those reached the Queue.

Conclusion

The concept of an event loop made Javascript more dynamic and flexible. It helps Javascript perform asynchronous programming, as it is single-threaded.

--

--