Question 90
Question
How does JavaScript's event loop handle microtasks vs macrotasks?
Answer
JavaScript's event loop is the heart of its asynchronous nature, managing how tasks are executed and ensuring a smooth user experience. Understanding how it handles different types of tasks, specifically microtasks and macrotasks, is crucial for writing efficient and responsive code.
1. Microtasks:
Purpose: Microtasks represent small, lightweight operations that usually occur within the web browser's event loop. They are often associated with asynchronous operations like setting up timers (
setTimeout
,setInterval
) or handling tasks deferred by Promises (then
callbacks).Execution:
Microtasks are always executed before macrotasks in each iteration of the event loop. This means that they have higher priority.
2. Macrotasks:
Purpose: Macrotasks encompass a wider range of operations, including:
Code execution from scripts.
Handling user interactions (e.g., button clicks).
Processing DOM manipulations.
Execution:
Macrotasks are executed after all microtasks have been processed in the current event loop iteration.
The Flow:
A macrotask is initiated (e.g., a user clicks a button).
The JavaScript engine pushes the macrotask onto the "Call Stack" – where tasks are actively being executed.
While the macrotask is running, it might trigger asynchronous operations (e.g., fetching data from a server) which create microtasks.
Once the current macrotask completes, the Call Stack becomes empty.
The JavaScript engine then checks the "Microtask Queue." If there are any microtasks waiting, they are executed one by one until the queue is empty.
Finally, if there are more macrotasks in the "Task Queue," a new macrotask is picked up and pushed onto the Call Stack, restarting the cycle.
Illustrative Example:
Output:
In this example, "Start" and "End" are macrotasks. setTimeout
creates a microtask that executes after both macrotasks are complete.
Last updated