Sub topic 11
Frame-Based Throttling with requestAnimationFrame
This chapter assumes you have read the earlier chapters on timestamp-based throttle and on preserving this and arguments. You should also know roughly how the browser event loop schedules rendering.
Why a Timer Is the Wrong Clock for Visual Work
A timer-based throttle with a wait of 16 ms looks like it matches a 60 Hz screen. In practice it does not. Timers are not synchronized with the browser's paint cycle. A timer callback can run just after a frame was painted, so its update waits almost a full frame before anyone sees it. Two callbacks can also land inside the same frame, and the first one's work is thrown away. Displays also vary: a 120 Hz or 144 Hz monitor refreshes far more often than every 16 ms.
requestAnimationFrame (rAF) solves this. It schedules a callback to run once, just before the browser's next repaint. The browser picks the rate, which usually matches the display's refresh rate. If you allow at most one rAF callback to be pending at a time, you get a throttle whose interval is exactly one frame.
The rAF Throttle
function rafThrottle(fn) {
let frameId = null;
let lastArgs;
return function (...args) {
lastArgs = args;
if (frameId === null) {
frameId = requestAnimationFrame(() => {
frameId = null;
fn.apply(this, lastArgs);
});
}
};
}
const box = document.querySelector('#box');
window.addEventListener('pointermove', rafThrottle((event) => {
box.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;
}));Here is what each part does:
frameIdrecords whether a frame callback is already scheduled. While it is non-null, later events only updatelastArgs.lastArgsis overwritten on every event, so the frame callback always uses the most recent pointer position. Older positions from the same frame are never drawn.- The arrow function inside
requestAnimationFramekeeps the wrapper'sthis, which follows the same pattern as the earlier chapter. frameIdis reset beforefnruns. Iffnthrows, the next event can still schedule a new frame.
This acts like a throttle with a trailing call: the latest state always gets handled, one frame later at most.
Adding cancel
Components that unmount, or elements that get removed, should drop a pending frame. cancelAnimationFrame plays the same role that clearTimeout did for debounce:
function rafThrottle(fn) {
let frameId = null;
let lastArgs;
function throttled(...args) {
lastArgs = args;
if (frameId === null) {
frameId = requestAnimationFrame(() => {
frameId = null;
fn.apply(this, lastArgs);
});
}
}
throttled.cancel = function () {
if (frameId !== null) {
cancelAnimationFrame(frameId);
frameId = null;
}
lastArgs = undefined;
};
return throttled;
}Gotchas and When Not to Use It
| Situation | Behavior | Implication |
|---|---|---|
| Background tab | rAF callbacks are paused | Fine for visuals; wrong for work that must keep running |
| High-refresh display | Callback runs 120+ times per second | Keep the handler cheap |
| Non-visual work (network, analytics) | Rate tied to screen, not need | Use a timer throttle or debounce instead |
| Layout reads in the callback | Reading `offsetWidth` after writes forces layout | Read first, then write |
Exercise
A developer throttles a canvas drawing handler with a 16 ms timestamp throttle. On a 144 Hz monitor the motion looks choppy, and sometimes the final pointer position is never drawn. Explain both problems and how rafThrottle fixes them.
Show answer
A 16 ms interval allows about 60 updates per second, but a 144 Hz display paints roughly every 7 ms, so many frames show no change and the motion looks choppy. The timer is also not aligned with paints. The timestamp throttle drops calls that arrive within the wait and has no trailing call, so the final position can be lost. rafThrottle runs once per actual frame at the display's rate and always uses the latest stored arguments, so the final position is drawn on the next frame.
Exercise
Why does the rAF callback set frameId = null before calling fn rather than after?
Show answer
If fn throws, code placed after the call never runs. frameId would stay non-null and every later event would skip scheduling, so the handler would stop working for good. Resetting it first keeps the throttle working after an error.