Introduction to Event loop, MacroTask, and Microtask in JavaScript in 2 mins !!
Table of contents
Event Loop, Macro Tasks, and Micro Tasks are three key concepts in JavaScript that help us understand how asynchronous operations work.
Event Loop
The event loop is a mechanism in JavaScript that allows asynchronous operations to be performed without blocking the main thread. It continuously monitors the call stack and the callback queue, and when the call stack is empty, it picks the next task from the callback queue and pushes it onto the call stack to be executed. The event loop ensures that only one task is executed at a time, and it guarantees that tasks are executed in the order they were added to the queue.
Macro Tasks
Macro tasks are tasks that are scheduled to be executed by the event loop after a certain period of time or when a certain event occurs. Examples of macro tasks include setTimeout, setInterval, setImmediate, I/O operations, and UI rendering. These tasks are executed after the current call stack is empty, which means that they are executed after all the micro tasks have been executed.
Example
console.log("Start");
setTimeout(function() {
console.log("Timeout");
}, 0);
console.log("End");
In this example, we use the setTimeout
function to schedule a function to be executed after a delay of 0ms. However, the output of this code is not what we might expect. The output will be:
Start
End
Timeout
The reason for this is that the setTimeout
function is a macro task, and it is scheduled to be executed after the current call stack is empty. Therefore, even though we schedule the setTimeout
function to be executed first, it is actually executed last after the current call stack is empty.
Micro Tasks
Micro tasks are tasks that are executed immediately after the current task and before any other macro tasks. Examples of micro tasks include Promise callbacks, process.nextTick, and mutation observers. Micro tasks are used to handle small and fast tasks that need to be executed before the next rendering cycle.
Example
console.log("Start");
Promise.resolve().then(function() {
console.log("Promise");
});
console.log("End");
In this example, we use a Promise to schedule a function to be executed as a micro task. The output of this code will be:
Start
End
Promise
The reason for this is that the Promise callback is a micro task, and it is executed immediately after the current task (which is the console.log("End")
statement) and before any other macro tasks.