Micro Tasks:
- Micro tasks are high-priority tasks in the event loop and are executed before macro tasks.
- They are usually used for tasks that need to be executed as soon as possible, such as promise resolution or DOM mutations.
- Micro tasks are added to the microtask queue (or job queue) and are processed in a first-in-first-out (FIFO) order.
- Micro tasks allow you to perform tasks between the completion of one task and the execution of the next one, ensuring that certain actions are taken before rendering updates or handling other asynchronous tasks.
- Examples of creating micro tasks:
- Promises (
.then() and .catch() callbacks)
process.nextTick() in Node.js
queueMicrotask() function in modern JavaScript environments
Macro Tasks (or Tasks):
- Macro tasks, often referred to simply as "tasks," are the low-priority tasks in the event loop.
- Examples of macro tasks include I/O operations (e.g., reading a file, making a network request), parsing and executing JavaScript code, and rendering updates to the user interface.
- Macro tasks are typically added to the callback queue (also known as the task queue) when their associated asynchronous operations are completed. They have a lower priority than micro tasks.
- Examples of creating macro tasks:
setTimeout()
setInterval()
XMLHttpRequest (AJAX) requests
- DOM events
<aside>
💡
The difference in priority between macro tasks and micro tasks can lead to specific execution behaviors. When the call stack is empty, the event loop checks and processes micro tasks before macro tasks. This behavior ensures that micro tasks are executed promptly, which is essential for tasks like promise resolution, making it easier to reason about the order of execution in certain asynchronous scenarios.
Here's a simplified flow of how macro and micro tasks are processed:
- Execute code in the call stack.
- Check for and execute any available micro tasks in the microtask queue.
- Check for and execute any available macro tasks in the task queue.
- Repeat steps 2 and 3 as long as there are tasks to process.
</aside>