Sub topic 12
Rendering and requestAnimationFrame in the Browser Loop
This chapter assumes you already know how one turn of the event loop works: the loop runs one task, then drains the microtask queue completely. It also assumes you are comfortable with promises and setTimeout. Here we add the piece browsers put on top of that model, which is the step where the page is drawn on screen.
Rendering Is a Step in the Loop
A browser does not repaint the page whenever your code changes the DOM. Repainting happens at one specific point in the event loop, called the update the rendering step. After a task finishes and the microtask queue is empty, the browser checks whether this is a rendering opportunity. A rendering opportunity is a moment when it makes sense to produce a new frame. On a 60 Hz display, that is about once every 16.7 ms. On a 120 Hz display, it is about once every 8.3 ms.
If it is a rendering opportunity, the browser runs a fixed sequence of work:
- It dispatches pending events tied to the frame, such as
resizeandscroll. - It runs requestAnimationFrame callbacks.
- It recalculates styles, computes layout, and runs
ResizeObserverandIntersectionObserverwork. - It paints the result and sends it to the compositor.
If it is not a rendering opportunity, the loop skips this step and goes on to the next task. Browsers can also skip frames when nothing visible has changed, or when the tab is hidden.
So rendering always happens between tasks. It never happens in the middle of one. Run-to-completion therefore applies to what the user sees: no intermediate state of a single task can ever reach the screen.
requestAnimationFrame: Running Code Right Before a Frame
requestAnimationFrame(callback) (rAF) asks the browser to call callback during the next rendering step, just before style and layout are computed. The callback gets one argument, a DOMHighResTimeStamp. This is the frame's start time in milliseconds, measured on the same clock as performance.now().
Here is a complete animation that moves a box 400 px at a constant speed, however fast the display refreshes:
const box = document.createElement('div');
box.style.cssText =
'width:50px;height:50px;background:teal;position:absolute;left:0;top:0';
document.body.appendChild(box);
const speed = 0.2; // pixels per millisecond
const distance = 400;
let startTime = null;
function step(timestamp) {
if (startTime === null) startTime = timestamp;
const elapsed = timestamp - startTime;
const x = Math.min(elapsed * speed, distance);
box.style.transform = `translateX(${x}px)`;
if (x < distance) {
requestAnimationFrame(step); // schedule the next frame
}
}
requestAnimationFrame(step);The key detail is that position comes from elapsed time, not from a frame count. If you move the box "5 px per frame", it moves twice as fast on a 120 Hz monitor and stutters when frames are dropped.
requestAnimationFrame returns an ID. Pass that ID to cancelAnimationFrame(id) to cancel a callback that has not run yet.
Which frame a callback runs in
Before running callbacks, the browser takes a snapshot of the rAF callback list. Every callback in that snapshot runs in this frame. A callback registered while those callbacks are running goes into the next frame. That is why the recursive step above runs once per frame and does not loop forever inside a single frame.
Microtasks between rAF callbacks
Each rAF callback is a separate invocation of script. When a callback returns and the call stack is empty, the browser runs a microtask checkpoint. So microtasks queued inside one rAF callback run before the next rAF callback:
requestAnimationFrame(() => {
console.log('raf 1');
Promise.resolve().then(() => console.log('microtask from raf 1'));
});
requestAnimationFrame(() => console.log('raf 2'));
// Output: raf 1, microtask from raf 1, raf 2Why Not setTimeout for Animation?
setTimeout(fn, 16) looks like it does the same job. It does not, because timers know nothing about frames.
| Concern | `setTimeout(fn, 16)` | `requestAnimationFrame(fn)` |
|---|---|---|
| Alignment with display refresh | None; drifts relative to frames | Runs once per frame, just before rendering |
| Callbacks per frame | Can be 0, 1, or 2, which causes jank | Exactly one (per registered callback) |
| High refresh displays | Stuck at about 60 updates per second | Matches 120 Hz, 144 Hz, and so on |
| Hidden or background tab | Throttled (often to 1 per second or less) but still runs | Usually paused entirely, which saves CPU and battery |
| Timestamp | Must call `performance.now()` yourself | Frame start time passed in |
The relative order of timers and rAF is also not something you can rely on. Try this in a console:
setTimeout(() => console.log('timeout'), 0);
requestAnimationFrame(() => console.log('rAF'));
Promise.resolve().then(() => console.log('microtask'));
console.log('sync');
// Output: sync, microtask, then 'timeout' and 'rAF' in either ordersync and microtask always come first. After that it depends on timing. If a rendering opportunity arrives before the timer task is picked, rAF prints first. Otherwise timeout prints first. Run it several times and you may see both orders.
Gotcha: Style Changes in One Task Collapse
Rendering happens only between tasks, so the browser sees only the final style a task leaves behind. A classic bug is a CSS transition that never plays:
const panel = document.createElement('div');
panel.style.cssText = 'width:50px;height:50px;background:tomato';
document.body.appendChild(panel);
panel.style.transition = 'transform 1s';
panel.style.transform = 'translateX(0)';
panel.style.transform = 'translateX(300px)'; // jumps instantly, no transitionThe browser never computed a style with translateX(0), so from its point of view there is no "before" state to transition from. Putting the second change in a single rAF does not fix it either. That rAF runs before style recalculation in the same frame, so both values still merge into one. The usual fix is a double rAF:
const panel = document.createElement('div');
panel.style.cssText = 'width:50px;height:50px;background:tomato;transition:transform 1s';
document.body.appendChild(panel);
requestAnimationFrame(() => {
// Frame 1: the starting style gets computed after this callback
requestAnimationFrame(() => {
// Frame 2: the start state has been rendered, so this change animates
panel.style.transform = 'translateX(300px)';
});
});Another approach is to force a style calculation by reading a layout property, such as panel.offsetWidth, between the two writes. That works, but it costs a synchronous layout.
Gotcha: Layout Thrashing
The browser normally delays layout until the rendering step. If your code reads a layout property (offsetHeight, getBoundingClientRect(), scrollTop) after writing styles, the browser has to compute layout immediately, in the middle of your task. This is called forced synchronous layout. If you alternate reads and writes in a loop, you trigger it on every iteration:
const items = Array.from({ length: 200 }, () => {
const el = document.createElement('div');
el.textContent = 'item';
document.body.appendChild(el);
return el;
});
// Slow: each read forces layout because the previous write invalidated it
for (const el of items) {
el.style.height = el.offsetWidth / 4 + 'px';
}
// Fast: read everything first, then write everything
const widths = items.map((el) => el.offsetWidth);
items.forEach((el, i) => {
el.style.height = widths[i] / 4 + 'px';
});The rule is to batch reads, then batch writes. Making DOM writes inside rAF callbacks helps, because they all land just before the layout the browser was going to do anyway.
Microtasks Cannot Let a Frame Through
The rendering step comes only after the microtask queue is completely empty. Code that keeps queuing promise callbacks therefore never yields to rendering, even though every piece of it is "asynchronous". A progress bar updated from a chain of .then() callbacks will not repaint until the chain ends. If you want the user to see each update, yield with a task (setTimeout) or wait for a frame (await new Promise(requestAnimationFrame)). A later chapter covers this starvation problem and how to fix it.
Exercises
Exercise
What does this log, and in what order? requestAnimationFrame(() => { console.log('A'); requestAnimationFrame(() => console.log('B')); Promise.resolve().then(() => console.log('C')); }); requestAnimationFrame(() => console.log('D'));
Show answer
A, C, D in the first frame, then B in the next frame. The microtask C runs at the checkpoint after the first callback returns, before D. B was registered during the frame's callback run, so it waits for the following frame.
Exercise
A developer sets el.style.opacity = '0', then immediately sets el.style.opacity = '1' in the same click handler, expecting a fade-in from a CSS transition on opacity. Nothing animates. Why, and what is one fix?
Show answer
Both writes happen in one task, and rendering happens only between tasks, so the browser computes only the final value of '1' and has no start state to transition from. Fix: set opacity to '0', then set it to '1' inside a nested double requestAnimationFrame, or force a style calculation (for example by reading el.offsetWidth) between the two writes.
Exercise
An animation moves an element by 4 px on every requestAnimationFrame callback. Users with 144 Hz monitors say it is too fast, and on a busy laptop it stutters. What change fixes both problems?
Show answer
Compute the position from elapsed time using the timestamp argument (position = (timestamp - startTime) * speed) rather than adding a fixed step per frame. Movement then no longer depends on refresh rate, and when frames are dropped the element jumps to the correct position.