JavaScript uses an event-driven architecture to manage asynchronous operations. When tasks such as timers, promises, or event handlers are executed, they are placed in different queues. Two important types of task queues are Microtasks and Macrotasks.
Understanding how microtasks and macrotasks work helps developers understand the JavaScript event loop and how asynchronous code is scheduled and executed.
What are Macrotasks?
Macrotasks are tasks that are placed in the main task queue and executed one by one after the current script execution is completed.
Examples of macrotasks include timers, DOM events, and network requests.
Examples of Macrotasks
- setTimeout()
- setInterval()
- DOM event handlers
- Network requests
Macrotask executed
What are Microtasks?
Microtasks are smaller tasks that are executed immediately after the current script finishes but before the next macrotask begins.
Microtasks have higher priority than macrotasks in the event loop.
Examples of Microtasks
- Promise.then()
- Promise.catch()
- Promise.finally()
- MutationObserver
Microtask executed
Execution Order Example
The following example shows how microtasks and macrotasks are executed by the event loop.
Start
End
Microtask
Macrotask
Even though the timer delay is zero, the microtask executes first because the microtask queue has higher priority.
Microtask vs Macrotask Difference
- Microtasks execute before macrotasks.
- Macrotasks run in the main task queue.
- Microtasks are usually related to promises.
- Macrotasks include timers and DOM events.
Why This Concept is Important
Understanding microtasks and macrotasks helps developers write more efficient asynchronous code and avoid unexpected execution order issues.
- Improves debugging skills
- Helps understand event loop behavior
- Ensures correct execution order in asynchronous code
- Improves performance of JavaScript applications
Conclusion
Microtasks and macrotasks play an important role in JavaScript's asynchronous execution model. Microtasks are executed first, followed by macrotasks, ensuring that promises and other high-priority tasks complete before scheduled timers and events.
By understanding how these task queues work with the event loop, developers can better control asynchronous behavior in JavaScript applications.
In the next tutorial, you will learn about the Fetch API in JavaScript, which allows developers to retrieve data from servers using HTTP requests.

