Categories
Javascript Tech

What is Event Loop & Micro and Macro Tasks in JavaScript?

Hello,

The basic concept behind the event loop working in Javascript engine!

Event Loop is a mechanism in JavaScript that handles asynchronous tasks in a non-blocking way. When JavaScript code is executed, it is run inside an event loop, which continuously checks if there are any tasks to be executed in the queue. The event loop is responsible for running the tasks in the queue, and it does this in a specific order.

The Event Loop in JavaScript has two main components: the Call Stack and the Callback Queue. The Call Stack is responsible for keeping track of the execution of the synchronous code. When a function is called, it is added to the top of the call stack, and when the function returns, it is removed from the top of the call stack.

The Callback Queue, on the other hand, is responsible for keeping track of the asynchronous tasks. When an asynchronous task is completed, it is added to the Callback Queue. The event loop continuously checks the Callback Queue to see if there are any tasks that can be executed. If there is a task, it is moved to the Call Stack, where it is executed.

Microtasks and Macrotasks are two types of tasks in JavaScript that are executed by the event loop.

Microtasks are tasks that are executed immediately after the current task has completed. Microtasks are executed before the next rendering of the web page, which means that they have a higher priority than Macrotasks. Some examples of Microtasks include Promises, MutationObserver, and process.nextTick in Node.js.

Macrotasks, on the other hand, are tasks that are executed after all the Microtasks have been executed. Macrotasks include tasks such as setTimeout, setInterval, and I/O operations in Node.js.

In summary, the Event Loop in JavaScript is responsible for handling asynchronous tasks in a non-blocking way. The Event Loop has two main components, the Call Stack and the Callback Queue. Microtasks and Macrotasks are two types of tasks that are executed by the event loop, and they have different priorities. Microtasks are executed before Macrotasks and are used for tasks that need to be executed immediately after the current task has completed, while Macrotasks are used for tasks that can be executed at a later time.

Source: AI Interaction Channels

Happy Learning!