Part 01 · How the Browser Works
The Frame Budget and requestAnimationFrame
At 60 fps every frame gets 16.6 ms. Where that budget goes, why the product carousel stutters, and how requestAnimationFrame lines work up with frames.
⏱ 6 min · Station 6 of 125
The problem
ShopLite's home page has a product carousel that slides continuously. It's smooth until the marketing team adds a "viewed products" tracker that runs a little JavaScript on every frame. Nobody sees an error, the tracker takes "only 20 ms", and the carousel now stutters.
20 ms sounds tiny. The question is: tiny compared to what? A frame at 60 frames per second lasts 16.7 ms, and the browser needs part of that for itself.
The idea
Screens refresh at a fixed rate, usually 60 times a second (some phones 90 or 120). To look smooth, the browser must hand the screen a new frame before each refresh: a frame budget of 1000 / 60 = 16.7 ms.
Inside that budget the main thread has to run your JavaScript, requestAnimationFrame callbacks, style, layout and paint. If the work takes longer, the frame isn't ready when the screen refreshes, and the previous picture stays up for one more refresh. That repeated picture is a dropped frame, and a run of them is jank.
How it works
- The display sends a vsync signal every 16.7 ms (at 60 Hz). The browser schedules frame work against these ticks.
- At the start of a frame, the browser runs the
requestAnimationFramecallbacks, passing each one the frame's timestamp. - Then style, layout and paint for whatever changed, and the result goes to the compositor.
- If everything finishes before the next tick, the frame shows. Your share of the budget is less than 16.7 ms, because the browser's own work comes out of it too. A common rule of thumb is about 10 ms for your code.
- If the work overruns, the next tick has nothing new. The screen repeats the old frame (a missed frame, 33.3 ms between updates), and the animation visibly hitches.
requestAnimationFrameruns once per frame, right before rendering, which makes it the right place for visual updates.setTimeout(fn, 16)doesn't line up with the vsync and drifts, so updates land mid-frame or twice in one frame.
Scrolling and CSS transform/opacity animations can continue on the compositor thread even when the main thread is late. A JavaScript-driven animation, like this carousel, can't.
The carousel moves in a requestAnimationFrame loop. You add 10 ms of extra JavaScript to every frame. What frame rate do you measure on a laptop?
Visual
Frame budgets compared
| Refresh rate | Budget per frame | Rough share for your code |
|---|---|---|
| 60 Hz | 16.7 ms | ~10 ms |
| 90 Hz | 11.1 ms | ~6 ms |
| 120 Hz | 8.3 ms | ~4 ms |
| Kind of animation | Needs the main thread every frame? | Survives a busy main thread? |
|---|---|---|
JS sets styles in requestAnimationFrame | yes | no |
JS sets styles in setTimeout / setInterval | yes, and not lined up with frames | no |
CSS transform / opacity animation | no | yes |
| Native scrolling | no (unless JS scroll listeners block it) | yes |
See it live
Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1 (headless Chrome produces frames at 60 Hz), no throttling, the lab in Docker on the same machine.
frames.html moves 12 slides with transform in a requestAnimationFrame loop, and adds ?work=N milliseconds of busy JavaScript to every frame. It records every frame's timestamp:
<!doctype html>
<html>
<head>
<title>frame budget</title>
<style>
body { margin: 0; overflow: hidden; font-family: system-ui; }
.track { display: flex; gap: 12px; will-change: transform; }
.slide { flex: 0 0 240px; height: 160px; border-radius: 10px; background: #ffcf70; display: grid; place-items: center; font-size: 28px; }
</style>
</head>
<body>
<div class="track" id="track"></div>
<script>
// A product carousel moved by JavaScript, one step per frame.
// ?work=N adds N ms of other JavaScript to every frame (analytics, a re-render, JSON parsing...).
const work = Number(new URLSearchParams(location.search).get("work") ?? 0);
const track = document.getElementById("track");
for (let i = 1; i <= 12; i++) track.insertAdjacentHTML("beforeend", `<div class="slide">#${i}</div>`);
const stamps = [];
let x = 0;
function frame(now) {
stamps.push(now);
const t = performance.now();
while (performance.now() - t < work) {}
x = (x + 4) % 1000;
track.style.transform = `translateX(${-x}px)`;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
// Called by the measuring script after the run.
window.report = () => {
const gaps = stamps.slice(1).map((s, i) => s - stamps[i]);
const secs = (stamps.at(-1) - stamps[0]) / 1000;
return {
frames: stamps.length,
fps: (gaps.length / secs).toFixed(1),
avgGap: (gaps.reduce((a, b) => a + b, 0) / gaps.length).toFixed(1),
worstGap: Math.max(...gaps).toFixed(1),
over20: gaps.filter((g) => g > 20).length,
};
};
</script>
</body>
</html>
tools/frames.mjs runs the carousel for 3 seconds with 0, 10, 20 and 40 ms of extra work:
// node frames.mjs: the carousel on frames.html for 3 seconds, with 0, 10, 20 and 40 ms of
// extra JavaScript in every frame. How many frames does the browser manage to show?
import { open, WEB } from "./lib.mjs";
console.log("extra work/frame frames in 3 s fps avg gap worst gap gaps > 20 ms");
for (const work of [0, 10, 20, 40]) {
const { browser, page } = await open();
await page.goto(`${WEB}/x/frames.html?work=${work}`, { waitUntil: "load" });
await page.evaluate(() => new Promise((r) => setTimeout(r, 3000)));
const r = await page.evaluate(() => window.report());
await browser.close();
console.log(`${(work + " ms").padStart(16)} ${String(r.frames).padStart(15)} ${r.fps.padStart(6)} ${(r.avgGap + " ms").padStart(10)} ${(r.worstGap + " ms").padStart(11)} ${String(r.over20).padStart(14)}`);
}
extra work/frame frames in 3 s fps avg gap worst gap gaps > 20 ms
0 ms 183 60.0 16.7 ms 16.8 ms 0
10 ms 183 60.0 16.7 ms 16.8 ms 0
20 ms 151 48.9 20.4 ms 33.4 ms 34
40 ms 77 24.6 40.6 ms 50.1 ms 76
Reading it:
- 0 ms and 10 ms: 60 fps, every gap 16.7 ms (worst 16.8). The 10 ms of work fit inside the budget, so the user can't tell it's there.
- 20 ms: 48.9 fps. 34 of the gaps were longer than 20 ms, and the worst was 33.4 ms: exactly two frame periods, a frame that never got drawn. The browser didn't drop every other frame, because its frame scheduling can shift a little, but about one frame in five was lost, and at a steady speed the eye reads that as stutter.
- 40 ms: 24.6 fps, average gap 40.6 ms. Every frame is now late by more than two vsyncs.
| Extra work per frame | fps | Frames lost in 3 s |
|---|---|---|
| 0 ms | 60.0 | 0 |
| 10 ms | 60.0 | 0 |
| 20 ms | 48.9 | 32 |
| 40 ms | 24.6 | 106 |
(Frames lost = the 183 frames shown with no extra work, minus the frames shown.) The jump isn't gradual: from 10 ms to 20 ms per frame, the frame rate went from perfect to visibly broken.
In real apps
- Carousels and progress animations use CSS animations (or the Web Animations API) on
transform, so a busy main thread doesn't freeze them. - Per-frame JavaScript is kept tiny. Trackers use
IntersectionObserver(the browser tells you when an element becomes visible) instead of measuring element positions on every frame or on every scroll event. - Scroll listeners are
passive: true, so the browser never has to wait for your handler before scrolling. - Test at 4x CPU slowdown and at 120 Hz. 10 ms of work that's fine at 60 Hz on a laptop breaks a phone's 120 Hz display or a 4x slower CPU.
What goes wrong in production
- Scroll handlers that do layout work (read
getBoundingClientRect, set styles) on every scroll event: scrolling janks on mid-range phones. - Animations driven by
setInterval(fn, 16): drifts against the vsync, so some frames get two updates and some none, even with plenty of budget. - A JSON parse, a React re-render or a GC pause landing mid-animation costs a few frames at random. The animation looks fine in a demo and hitches in real use.
- 120 Hz screens: work tuned to "under 16 ms" now overruns a budget of 8.3 ms.
Key takeaway
At 60 Hz the browser has 16.7 ms per frame, and your code gets only part of it. Work that fits is free; work that doesn't costs whole frames at once. Keep per-frame JavaScript small, and let the compositor run animations whenever you can.
Practice
Find the breaking point. Predict the frame rate with 12, 14 and 16 ms of extra work per frame, then with 10 ms of work on a 4x slower CPU (open({ cpu: 4 }) in frames.mjs). Change the list in frames.mjs and run it.
Answer
Our runs: 12 ms gave a clean 60.0 fps; 14 ms and 16 ms gave 59.7 fps with one 33 ms gap each. The browser's own work for this page is small (one transform on one element), so almost the whole 16.7 ms was available, and the frames only started to slip once the work got close to the full budget.
10 ms on a 4x slower CPU gave 56.5 fps, 9 gaps over 20 ms, and a worst gap of 50 ms (two missed frames in a row). The busy loop itself still took 10 ms (it waits on the clock), but the browser's style and paint work became 4 times slower and no longer fit next to it. That's the phone case: the same code that has room to spare on a laptop drops frames on a mid-range device. Budget for the slowest device you support, not for your own machine.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →