The Event Loop: Tasks, Microtasks and Rendering
Explain how the JavaScript runtime schedules one task at a time, why promise callbacks jump ahead of timer callbacks, and what a long task does to a page.
Contentsand lesson path
On this page
- Why it matters
- One thread, two queues
- Watch it run
- Blocking the loop
- Check your understanding
- Apply it
- Review prompt
Lessons of Async JavaScript & Fetch
- The Event Loop: Tasks, Microtasks and Rendering Concept · 20 min
- Promises and async/await Without Surprises Worked example · 25 min
- Talking to an HTTP API with fetch Worked example · 25 min
- Cancellation, Debouncing and Out-of-Order Responses Concept · 20 min
- Lab: Search-as-You-Type Against a Public API Lab · 30 min
- Check: Execution Order and Failure Modes Knowledge check · 8 questions
What you will learn
- Explain how the event loop schedules tasks and microtasks and predict the execution order of mixed synchronous, promise and timer code.
Prerequisites: JavaScript Foundations
01. Why it matters
JavaScript in a browser runs your code on a single thread: one piece of code executes at a time, and while it executes nothing else in that page can run. Asynchronous code — timers, network responses, event handlers — is the trick that keeps one thread useful: slow work gets queued, and the thread carries on. To predict what such code will do, you need the scheduling model underneath it: the event loop, the task queue and the microtask queue.
This model is not just interview trivia. It answers everyday questions: why a log line prints after the function that called it has finished, why a spinner does not appear even though you set it before starting a network request, why a timer fired late, and why the page froze while a loop was running. The next lessons build fetch and async/await on top of this model.
02. One thread, two queues
The runtime keeps two waiting areas. The task queue holds whole jobs: timer callbacks from setTimeout and setInterval, I/O callbacks, and event handlers such as click or input. The microtask queue holds small follow-ups: promise reactions (the callbacks registered with then, catch and finally), callbacks from queueMicrotask, and the code after an await.
Why two queues? They answer different needs. A task is a unit of work the browser or Node decided to schedule: respond to a click, run an expired timer, act on received bytes. A microtask is a follow-up that must happen as soon as the current code finishes, before anything else gets a turn — a promise callback has to run while the state it belongs to is still fresh, before the browser can paint something half-updated. Splitting the two queues gives both guarantees without a second thread.
The event loop repeats one rhythm, described in the MDN execution model notes:
1. take one task from the task queue
2. run it to completion (nothing else runs meanwhile)
3. drain the microtask queue completely,
including microtasks added while draining
4. if due: resize steps, animation frames, paint
5. pick the next task and start againTwo consequences follow from the rhythm. First, promise callbacks that are already queued run before the next timer, because microtasks are drained after every task and timers are tasks. (A callback on a promise that is still pending — say, one resolved by a later timer or a network reply — waits until that promise settles.) Second, setTimeout(fn, 0) never means "run in exactly 0 ms": the delay is a minimum, and the callback still waits for the current task to finish, for the microtask queue to drain, and for every task already ahead of it in the queue. Browsers also clamp deeply nested timers to at least 4 ms after five levels of nesting.
Rendering slots in at step 4, between tasks. A browser repaints the page only when the thread is free, so animation frames and clicks all wait behind whatever task is running. The demos in this lesson run in Node.js (tested with 22.23), which implements the same task and microtask rules; the browser adds the rendering step. (Node also has a process.nextTick queue of its own, which browsers do not have — ignore it while you learn the model here.)
03. Watch it run
Read the script below and predict the order of the log lines before looking at the output. Try to name, for each line, whether it is synchronous code, a task or a microtask.
console.log('sync: start');
setTimeout(() => {
console.log('task: timer one (0 ms)');
Promise.resolve().then(() => console.log('micro: scheduled inside timer one'));
}, 0);
setTimeout(() => console.log('task: timer two (0 ms)'), 0);
Promise.resolve()
.then(() => console.log('micro: first'))
.then(() => console.log('micro: chained (queued by the first)'));
console.log('sync: end');sync: start
sync: end
micro: first
micro: chained (queued by the first)
task: timer one (0 ms)
micro: scheduled inside timer one
task: timer two (0 ms)Walk the output against the rhythm. Both console.log calls are the first task, so sync: start and sync: end print before anything queued. Draining the microtask queue runs micro: first, and that callback queues micro: chained, which runs in the same drain — the queue is emptied completely, not one microtask per turn. Only then does the event loop take the next task: timer one, whose own microtask runs before timer two gets its turn.
The same rule explains await: an async function runs synchronously up to the first await, and the rest of the function is queued as a microtask once the awaited value has settled, exactly like a then callback. That is why code after an await can still be overtaken by code that never paused.
04. Blocking the loop
Because there is one thread, a long synchronous task delays everything queued behind it — timers, click handlers, paint work, all of it. The next script requests a timer with a 50 ms delay, then blocks the thread with a 300 ms loop:
setTimeout(() => console.log('task: timer fired (requested at 50 ms)'), 50);
const start = Date.now();
while (Date.now() - start < 300) {
// block the single thread for 300 ms
}
console.log('sync: loop done, 300 ms or more:', Date.now() - start >= 300);sync: loop done, 300 ms or more: true
task: timer fired (requested at 50 ms)The timer was eligible after 50 ms, but it ran at about 300 ms: it could not interrupt the running task. In a browser the effect is visible without a console. While a task runs, no paint happens, so animations stop, scroll freezes, and clicks queue up to be handled later. This is also why a spinner you switch on and a loop you start in the same task never meet: the browser only paints between tasks, so the spinner would appear only after the loop finishes. A "long task" is any task that hogs the thread this way; keeping your handlers short — splitting heavy work into steps that yield to the event loop (e.g. with await new Promise((r) => setTimeout(r)), or scheduler.yield() where it exists: Chromium-based browsers and Firefox have it, Safari does not yet, so feature-detect it) — is what keeps a page responsive.
The habit to take away: do not busy-wait on the main thread. If you need something to happen later, queue it (setTimeout, a promise, or an event) and let the loop turn.
05. Check your understanding
06. Apply it
This skill builds towards a search-as-you-type UI, and every bug you will meet there is a scheduling bug in disguise. Two exercises to do now, in a browser console or an *.mjs file:
- Write a script that mixes
console.log,setTimeout(…, 0),Promise.resolve().then(…)and oneasyncfunction with anawait. Predict the full order on paper first, then run it. If your prediction was wrong, name the exact rule you missed. - In the browser, paste a handler that runs a 500 ms
whileloop, then click around while it runs. Watch how the clicks are handled only after the loop ends — that queueing is the event loop, not the handler.
07. Review prompt
Without looking back: list the five steps of one event-loop turn in order. Which queue holds timer callbacks, which holds promise reactions, and what happens to microtasks that are queued while the microtask queue is draining? Finally, explain in one sentence why setTimeout(fn, 0) can fire later than 0 ms, and what a long task does to rendering.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.