JavaScript Event Loop Explained: Tasks, Promises, and Microtasks
Understand browser JavaScript task and microtask order, promise callbacks, timers, rendering opportunities, and main-thread responsiveness.
The browser JavaScript event loop coordinates synchronous code, queued tasks, promise callbacks, and rendering. This guide traces the order with a runnable example, explains microtask starvation, and shows how to choose the right scheduling tool for responsive interfaces.
JavaScript in a browser often runs on a main thread that also handles user events and page rendering. The event loop coordinates when queued work gets a turn. Understanding that order explains why a promise callback can run before a timer, why setTimeout(fn, 0) is not immediate, and why a page may stop responding even when code uses asynchronous APIs.
A practical model of one event-loop turn
For browser code, a useful simplified model is: run one available task to completion, drain the microtask queue until it is empty, then give the browser a chance to update rendering before the loop continues. The browser may skip a render opportunity when no update is needed. The important point is that JavaScript execution in a task is run-to-completion: another event handler does not interrupt halfway through a synchronous function.
“Macrotask” is a common informal name for a task. The HTML Standard and browser documentation use task and microtask queues. Different task sources can be scheduled according to browser rules, so avoid assuming every timer, input event, and network callback has one universal global FIFO ordering.
Trace synchronous code, promises, and timers
console.log('A: sync start');
setTimeout(() => console.log('D: timer task'), 0);
Promise.resolve().then(() => {
console.log('C: promise microtask');
});
queueMicrotask(() => {
console.log('C2: queued microtask');
});
console.log('B: sync end');
The synchronous logs appear first: A, then B. After the current JavaScript stack finishes, promise reactions and queueMicrotask() callbacks run as microtasks in the order they were queued, so C then C2 run before the timer callback. The timer callback is a later task; a zero delay means the timer is eligible after its delay, not that it interrupts the current code or runs at precisely zero milliseconds.
When an async function reaches await, its continuation is scheduled to resume later as a microtask after the awaited value settles. The synchronous code after calling the function can therefore run before the continuation. Treat await as a clear way to write promise-based asynchronous flow, not as a way to move CPU-heavy synchronous work off the main thread.
Microtasks run before the next task
Promise reactions and callbacks passed to queueMicrotask() use the microtask queue. Once microtask processing begins, the browser continues until that queue is empty, including microtasks added by other microtasks. This makes microtasks useful for short, ordered follow-up work after the current operation finishes.
That drain behavior can also cause trouble. If a microtask continually queues another microtask, the queue may never empty. The browser then has little opportunity to process another task or update the page. Keep microtask callbacks short; they are not a background-work queue and do not make expensive loops responsive.
Rendering and long tasks
Because a synchronous task runs to completion, a long loop or expensive computation can delay click handling, input, and painting. Splitting work into smaller chunks gives the event loop opportunities to process other work between chunks. For CPU-heavy calculations, a Web Worker can move computation away from the UI thread, though workers do not directly manipulate the page DOM.
Do not use a long chain of resolved promises as a yield strategy: each continuation remains a microtask, and the queue is drained before the next task. For visual updates, coordinate work with browser rendering APIs where appropriate. For background or non-urgent work, choose a scheduling mechanism based on its support and priority needs, and provide a fallback if the browser API is not universal for your target users.
Choose the scheduling tool by intent
| Need | Typical tool | Remember |
|---|---|---|
| Run after the current stack, before the next task | queueMicrotask() or a promise reaction | Keep work short; recursive scheduling can starve other work. |
| Run after a delay or on a later task | setTimeout() | Delay is a minimum, not an exact execution time. |
| Continue after an asynchronous result | await or .then() | Continuation runs later; it does not offload CPU work. |
| Keep heavy computation away from the UI thread | Web Worker | Communicate through messages; DOM access stays on the main thread. |
The right choice depends on whether the code is ordering work, waiting for a timer, reacting to I/O, synchronizing a small follow-up, or doing expensive computation. A timer is not a precision clock, a microtask is not a worker, and an async keyword does not make a synchronous loop non-blocking.
Debug execution order with small probes
- Write a minimal example with labels in each log statement.
- Separate synchronous logs, promise reactions,
queueMicrotask(), timers, and rendering callbacks. - Observe the browser's console, then add one callback type at a time.
- Measure long synchronous work with the Performance panel and look for delayed input or rendering.
- For production logic, test observable outcomes instead of depending on incidental timing between unrelated task sources.
Once you know which queue a callback uses, unexpected ordering becomes easier to explain. The event loop coordinates the browser's work; your code should keep each turn short enough for the browser to remain responsive.
References and related learning
- MDN: Using microtasks in JavaScript
- MDN: Microtasks and the JavaScript runtime
- WHATWG HTML Standard: Event loops
For related browser behavior patterns, see our guides to debounce and throttle and event delegation.
Want a structured Java learning path?
Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.