Understanding the JavaScript Event Loop

Introduction

JavaScript is a very popular programming language introduced by Brendan Eich in 1995. It was built with the intention of adding interactivity and dynamic features to the HTML web pages. JavaScript made the web applications more advance because this programming language supports asynchronous operations, meaning it can execute the ramaining part of the code at the same time while waiting for a certain task to finish which is taking a longer time to execute.

JavaScript event loops are defined as a mechanism for performing asynchronous and synchronous operations in programming despite being a single-threaded language. Event loop ensures to execute the code in the right order without blocking.

Components in JavaScript Event Loop

  1. Call Stack

A call stack is a mechanism in JavaScript for an interpreter to manage the code. The call stack execute the code in LIFO (Last In First Out) order. It cannot handle asynchronous tasks directly. Whenever an asynchronous functions is called like setTimeout or fetch, then that functions are passed to Web APIs(browser/Node.js environment) and when completed, its callback is sent to the task queue (or callback queue).

The asynchronous tasks are handled outside the call stack and re-enter via queues when ready. The event loop moves the callback into the call stack only when the loop is empty.

Example

// JavaScript program to demonstrate the working of call stack

console.log(“This sentence will print first”);

setTimeout(() => {

console.log(“This sentence will print at last”); // Asynchronous task

}, 2000);

console.log(“This sentence will print second”);

Output

This sentence will print first

This sentence will print second

This sentence will print at last

  1. Web APIs(Browser/Node APIs)

Web APIs are used to handle asynchronous task in JavaScript to prevent the blocking of code and ensure the smooth execution without blocking the main thread. When the asynchronous task is completed, Web APIs push the callback function to a queue which are futher passed to event loop. Event loop passes the completed asynchronous task to the call stack.

  1. Callback Queue(Task Queue)

The callback queue or task queue is a fundamental mechanism for handling asynchronous tasks in JavaScript. This mechanism allows JavaScript to handle the events efficiently, preventing long-running tasks from freezing the main thread, and to perform non-blocking input/output operations.

Given below are the different characteristics of the Callback Queue in JavaScript.

  • Storage for Asynchronous Callbacks: When asynchronous operations like setTimeout, fetch, and DOM event is completed its background processing is done, then their callback function is not immediately executed. Instead, it is stored in the callback queue.
  • FIFO(First-In , First-Out) : The callback queue follows the FIFO principle, meaning the callbacks are processed in the order in which they are placed in a queue. The first callback to enter the queue will be the first to move to the call stack for execution.
  • Interaction with Event Loop: Callback queue interacts with the event loop as the event loop continuously track the call stack and callbacks queue. Once the call stack is empty , the event loop checks for the callback queue. If there is any callback awaiting , then the event loop takes the first one from the callback queue and push it into the callstack for execution.
  1. Microtask Queue

The microtask queue in JavaScript are a higher priority queue than the callback queue. The Microtask Queue hold the task that needs to be executed on a higher priority. The task stored in microtask queue will execute first before any task stored in the macrotask(callback queue). The microtask queue in JavaScript handles the promise callbacks. When a promise resolves or rejects , the block of code placed inside the try, catch, and finally keywords are placed in a mocrotask queue in order to execute that block of code as soon as the compiler finishes the current execution. The event loop will first empty the microtask queue before start processing the macrotask queue(or callback queue).

  1. Event Loop

­­­­­­­­­­The Event loop is the core mechanism in JavaScript for handling asynchronous tasks. The following are the two things that are continuously monitored by Event Loop:

  • Call Stack: The Call stack performs the synchronous function, and it follows the LIFO principal(Last-in, First-Out). If the call stack is empty, then it means no synchronous task is left to be performed, and the event loop can proceed.
  • Queues: Queues are divided into categories. First is microtask queue and the second one is macrotask queue(or callback queue). Microtask stores the task that needs to be performed with higher priority. It mainly stores the promises, async/await callbacks , and Mutation Observer. If the microstack is empty, then the event loop will start executing the callback queue, which mainly stores setTimeout, setInterval, DOM events, and setImmediate. The data stored in a callback queue are processed in a FIFO(First-In, First-Out) order.

Conclusion

This article describes the event loop in JavaScript. The event loop in JavaScript comprises different sections, and this article explains all those important sections which play a major role in performing asynchronous operations in JavaScript.

If you are looking for more such kind of article for gaining a knowledge in programming, I suggest you to visit the Tpoint Tech Website where you can get varios articles in programming and in other technology as well along with interview questions, working codes and online compiler where you can run your code easily.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply