“The Event Loop is a mechanism that allows JavaScript to perform non-blocking operations by managing the execution of multiple tasks (synchronous and asynchronous) on a single thread.” - MDN docs.

Event loop empowers JavaScript’s single-threaded structure to handle multiple operations concurrently on different threads without needing multi-threading.

Category of Tasks in the Event Loop

1. Microtasks

Microtasks are callback functions associated with Promises and other asynchronous operations. They include methods like .then(), .catch(), and .finally () and operations triggered by MutationObserver.

2. Macrotasks

Macrotasks are callback functions associated with browser APIs such as setTimeout(), setInterval(), or network requests. They also include DOM-related events like click, keydown, and similar user interactions.

3. Top-Level Code / Synchronous Code

This includes the entire JavaScript file, script that is executed line by line in the order it is written. It runs before any tasks in the Microtask or Macrotask Queues.

4. Rendering Tasks

Rendering tasks include browser UI-related operations, such as reflows, repaints, and DOM updates. These tasks ensure that changes made by JavaScript are visually reflected on the screen.

Components in the Event Loop

1. Call Stack

The Call Stack is a container, implemented as a FILO (First In, Last Out) stack, used by the JavaScript engine to track function calls. Functions are added to the stack when they are called and removed when they return. It is where synchronous code is executed.

2. Microtask Queue

The Microtask Queue stores Microtasks like resolved Promise callbacks or MutationObserver tasks. Microtasks are executed immediately after the current stack is cleared and before moving to the Macrotask Queue.

3. Macrotask Queue

The Macrotask Queue stores Macrotasks, which include callbacks for APIs like setTimeout(), setInterval(), and DOM events. Macrotasks are processed only after all Microtasks have been cleared.

4. Web APIs