Sub topic 12
Rendering and requestAnimationFrame in the Browser Loop
This chapter assumes you know how one turn of the event loop runs a task and then drains the microtask queue. It also assumes you can run code in a browser console. Node.js has no rendering step, so everything here applies only to browsers.
Rendering Is a Step in the Loop
The browser does not repaint the screen whenever you change the DOM. It updates the page only at a rendering opportunity, which comes after a task finishes and the microtask queue is empty. Most displays refresh at about 60 Hz, so the browser tries to render roughly every 16.7 ms. It may skip rendering on a turn if nothing changed or a frame isn't due yet.
When the browser does render, it runs these steps in order:
- Run
requestAnimationFrame(rAF) callbacks. - Recalculate styles.
- Compute layout, meaning the size and position of each element.
- Paint the result to the screen.
Changes Inside One Task Are Never Painted Separately
Rendering cannot happen while a task is running, so the user never sees intermediate DOM states from a single task:
const box = document.createElement('div');
box.textContent = 'box';
document.body.appendChild(box);
box.style.background = 'red';
box.style.background = 'blue';
box.style.background = 'green';
// The user only ever sees green.The same rule applies to microtasks. A promise chain that updates the DOM 1,000 times still produces a single paint, because the microtask queue must be completely empty before rendering can start.
Why requestAnimationFrame Beats setTimeout for Animation
requestAnimationFrame(callback) schedules callback to run once, just before the next paint. The browser passes it a high-resolution timestamp. Animating with setTimeout(fn, 16) has two problems. Timer delays are only minimums, and timers are not lined up with frames. Some frames get two updates and others get none, which shows up as stutter. rAF runs exactly once per frame, at the moment where changes will be painted.
const box = document.createElement('div');
box.style.cssText = 'width:50px;height:50px;background:teal;position:absolute;';
document.body.appendChild(box);
let startTime = null;
function step(timestamp) {
if (startTime === null) startTime = timestamp;
const elapsed = timestamp - startTime;
// Move 0.2 px per ms, stop at 400 px
const x = Math.min(elapsed * 0.2, 400);
box.style.transform = `translateX(${x}px)`;
if (x < 400) {
requestAnimationFrame(step); // schedule for the NEXT frame
}
}
requestAnimationFrame(step);The animation computes position from elapsed time rather than counting frames, so it moves at the same speed on 60 Hz and 120 Hz screens.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `setTimeout` for animation | Frames are skipped or doubled, causing jank | Use `requestAnimationFrame` |
| Assuming a fixed frame rate | Animation speed changes on high-refresh displays | Base motion on the timestamp |
| Expecting rAF in background tabs | Browsers pause rAF in hidden tabs | Don't rely on rAF for non-visual work |
| Reading layout right after writing styles | Forces a synchronous layout (layout thrashing) | Batch all reads, then all writes |
Exercise
A click handler sets an element's text to "Loading...", then runs a synchronous loop that takes 2 seconds, then sets the text to "Done". What does the user see, and why?
Show answer
The user sees the old text for about 2 seconds and then "Done". They never see "Loading...". All three steps run inside one task, and rendering can only happen after the task and its microtasks finish, so only the final state gets painted.
Exercise
In what order do these logs appear? requestAnimationFrame(() => console.log('raf')); setTimeout(() => console.log('timeout'), 0); Promise.resolve().then(() => console.log('micro')); console.log('sync');
Show answer
'sync' prints first, then 'micro'. After that, 'timeout' and 'raf' can come in either order. 'timeout' usually prints before 'raf', but if a frame is due right away, rAF runs at that rendering opportunity before the timer task. Never write code that depends on the order of timers relative to rAF.