The Event Loop, Tasks, and Microtasks
Build an accurate mental model of what the browser does, from navigation and HTTP through parsing, rendering, storage, workers, security, and DevTools, so you can predict behavior and debug real pages.
What you will be able to do
#- Predict output order of synchronous, microtask, and task work.
- Explain when rendering steps run relative to tasks.
- Use requestAnimationFrame for visual updates.
Overview
#JavaScript runs on a single main thread with a run-to-completion model.
The loop
The event loop picks one task from the task queue, runs it to completion, then drains the entire microtask queue, then may run rendering steps such as requestAnimationFrame callbacks, style, layout, and paint.
Tasks and microtasks
- Tasks:
setTimeout,setInterval, message events, I/O callbacks. - Microtasks: promise callbacks,
queueMicrotask,MutationObserver.
Microtasks run before the next task and before rendering, so a microtask that schedules another microtask can starve rendering.
Ordering example
console.log('1');
setTimeout(() => console.log('2'), 0);
Promise.resolve().then(() => console.log('3'));
console.log('4');
Output: 1, 4, 3, 2. The synchronous logs run first, then the microtask, then the task.
requestAnimationFrame
requestAnimationFrame callbacks run before paint in the rendering steps. Use them for visual updates so work is batched into a frame.
Questions to carry forward
- Can microtasks starve rendering?
- Where do requestIdleCallback callbacks run?
- Why does setTimeout(0) not run immediately?
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What is the console output order?
starter.javascriptconsole.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4');Reveal the reference answer
reference.javascript1, 4, 3, 2Authored expected output: 1 4 3 2
Synchronous logs run first (1 and 4), then the microtask queue drains (3), then the timer task runs (2).
Exercise 2Predict
Which queue drains first after the current task finishes?
Common misconceptions
#- setTimeout with 0 runs before promise callbacks.
- Microtasks run after rendering.
- requestAnimationFrame runs after paint.
Follow-up practice
#- browser-internals-dom-events
- browser-internals-web-workers
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.