What are microtasks and macrotasks?
Modern JavaScript runs on a single-threaded event loop. It executes code, handles events and renders the UI by processing a queue of tasks one after the other. To keep the browser responsive, the runtime splits work into macrotasks (also called "tasks") and microtasks. Understanding the difference helps you predict when your code will run and how it interacts with the rest of the page.
What is a macrotask?
Macrotasks represent the "big" units of work handled by the browser. Each macrotask comes from a different source: an entire script block, a callback from an event (click, scroll, etc.), timers like setTimeout() and setInterval(), or I/O such as network responses. The event loop picks one macrotask from the queue, runs it to completion (including any synchronous code), then moves on to the next one. Because the browser only processes one macrotask at a time, long-running tasks can block rendering and make the page feel sluggish.
What is a microtask?
Microtasks are tiny jobs that must run after the current macrotask finishes but before the browser does anything else. They're created by promises (.then, .catch and .finally callbacks) and the queueMicrotask() API When a macrotask ends, the event loop empties the microtask queue — executing each microtask in order — before it renders the page or processes the next macrotask. This guarantees that promise handlers always run after the code that scheduled them, but before other asynchronous events.
How the event loop orders them
The simplified event loop behaves like this:
- Run a macrotask (e.g., an event handler or
setTimeoutcallback). - When that macrotask finishes, execute all pending microtasks. If a microtask queues more microtasks, they run before the loop continues
- Render updates and handle UI painting.
- Repeat with the next macrotask
Because microtasks run before rendering and before the next macrotask, they have higher priority. This ensures that promise chains update data consistently and avoids race conditions. However, a microtask that continually re-queues itself can starve rendering and freeze the UI.