Sub topic 11
Frame-Based Throttling with requestAnimationFrame
This chapter assumes you have already built the timestamp-based throttle from earlier in the tutorial. It also assumes you know how closures capture variables, how Function.prototype.apply forwards this and arguments, and how the event loop runs callbacks between tasks. Here you replace the fixed millisecond interval with the browser's own rendering schedule.
Why a Fixed Interval Is the Wrong Clock for Visual Work
A timer-based throttle runs a handler at most once every wait milliseconds. That suits work like logging scroll depth or sending analytics, where the exact rate does not matter much. Visual updates are different. The browser draws the screen in frames, usually 60 per second (about 16.7 ms each), and 120 or more on high-refresh displays. Any DOM change you make between two frames is only seen when the next frame is drawn.
Suppose you throttle a pointermove handler to 16 ms with setTimeout or Date.now(). Two problems show up:
- Drift. Timer callbacks are not tied to frame boundaries. Sometimes two handler runs land inside one frame and the first one is wasted work. Sometimes no run lands in a frame and the element visibly stutters.
- Wrong rate on other displays. A 16 ms interval is too slow for a 120 Hz screen and wastes work on a 30 Hz power-saving mode.
requestAnimationFrame (rAF) schedules a callback to run right before the browser's next repaint. If you use it as the throttle's clock, you get at most one update per frame, matched to the display's real refresh rate, with no interval to tune.
How the rAF Throttle Works
The pattern is short. Each event stores its latest arguments. If no frame is scheduled yet, the event schedules one. When the frame callback runs, it clears the "scheduled" flag and calls the handler with the most recent arguments.
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)`;
}));Pay attention to these details:
frameIdserves as the throttle's state. While it isnull, no frame is pending. While it holds a number, later events only updatelastArgs.frameId = nullruns beforefn.apply. If the handler throws, the throttle still resets, and the next event can schedule a new frame.lastArgsis overwritten on every event, so the frame always uses the newest pointer position. This is a trailing behavior by design. The intermediate positions are dropped because the user would never see them.- No
waitparameter is needed, because the browser decides the timing.
Gotcha: Which `this` Does the Handler Get?
The arrow function passed to requestAnimationFrame captures this from the wrapper call that scheduled the frame. That is the first call in the frame. lastArgs, by contrast, comes from the last call. For DOM listeners this rarely matters, because every event on one listener has the same this (the element). It does matter if you share one throttled function between several objects as a method. The handler could then run with object A's this and object B's arguments.
The fix is the one you used in the trailing throttle: store this alongside the arguments.
A Production-Ready Version with cancel
Pending frames can outlive the thing they update. If a component removes #box from the page, a queued frame can still try to write to it. Add a cancel method that calls cancelAnimationFrame, just as the debounce in the cancel and flush chapter calls clearTimeout.
function rafThrottle(fn) {
let frameId = null;
let lastThis;
let lastArgs;
function run() {
const ctx = lastThis;
const args = lastArgs;
frameId = null;
lastThis = undefined;
lastArgs = undefined;
fn.apply(ctx, args);
}
function throttled(...args) {
lastThis = this;
lastArgs = args;
if (frameId === null) {
frameId = requestAnimationFrame(run);
}
}
throttled.cancel = function () {
if (frameId !== null) {
cancelAnimationFrame(frameId);
}
frameId = null;
lastThis = undefined;
lastArgs = undefined;
};
return throttled;
}
const box = document.querySelector('#box');
const onMove = rafThrottle(function (event) {
box.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;
});
window.addEventListener('pointermove', onMove);
function teardown() {
window.removeEventListener('pointermove', onMove);
onMove.cancel();
}Clearing lastThis and lastArgs after each run frees the reference to the event object. Remove the listener and cancel. Removing the listener alone leaves a frame that may already be queued.
Timer Throttle vs rAF Throttle
| Aspect | Timer-based throttle | rAF throttle |
|---|---|---|
| Clock | `wait` milliseconds you choose | Display refresh rate |
| Alignment with paint | None, so it can drift | Runs right before paint |
| Hidden or background tab | Timers keep running (browsers clamp them to about once per second or slower) | Paused entirely |
| Configurable rate | Yes | No, one call per frame |
| Available outside browsers | Yes (Node.js, workers with timers) | Browser main thread and some workers only |
| Best for | Network calls, analytics, non-visual state | DOM writes, canvas drawing, transforms |
Edge Cases and Failure Modes
Background tabs stop the callbacks
Browsers pause rAF callbacks in hidden tabs. A rAF throttle around anything that must run, such as saving state or sending a final position to a server, will silently stall until the user comes back. Keep non-visual work on a timer-based throttle or debounce. Let rAF handle only the drawing.
Splitting reads from writes
A rAF callback runs before style and layout are calculated for the frame. If the handler writes a style and then reads a layout property like offsetWidth, the browser must run layout synchronously. That forced reflow costs the time you were trying to save. Do your reads in the event handler or at the start of the callback, and your writes at the end:
const panel = document.querySelector('#panel');
const onScroll = rafThrottle(function () {
const y = window.scrollY; // read first
const height = panel.offsetHeight; // read
panel.style.opacity = String(Math.max(0, 1 - y / height)); // write last
});
window.addEventListener('scroll', onScroll, { passive: true });The { passive: true } option tells the browser the listener never calls preventDefault, so scrolling does not have to wait for your JavaScript.
Dropped intermediate points
For dragging a box, using only the latest position per frame is correct. For a drawing app, the dropped points become jagged lines. Pointer events offer event.getCoalescedEvents(), which returns the high-resolution points the browser merged into one event. Accumulate those into an array between frames and draw them all in the callback, rather than keeping only lastArgs.
Slow handlers still hurt
rAF limits how often the handler runs, not how long it takes. A handler that needs 30 ms each frame still drops you to about 30 frames per second. If profiling shows long frames, the fix is less work per frame, not a different throttle.
Testing
Jest's modern fake timers also fake requestAnimationFrame in jsdom. jest.advanceTimersByTime(16) advances one frame, and jest.advanceTimersToNextFrame() is available in recent Jest versions. In environments without rAF, you can inject the scheduler: write rafThrottle(fn, schedule = requestAnimationFrame, cancel = cancelAnimationFrame) and pass timer-based stand-ins in tests.
Exercises
Exercise
A user moves the pointer and fires 9 pointermove events within a single 16.7 ms frame on a 60 Hz display. How many times does the handler wrapped by rafThrottle run for that frame, and with which event?
Show answer
Once. The first event schedules the frame and the next 8 only overwrite lastArgs, so the handler runs before the repaint with the ninth (latest) event.
Exercise
You use rafThrottle to send the current scroll position to an analytics endpoint. Users report that positions from when they switched tabs mid-scroll are missing. Why, and what should you change?
Show answer
Browsers pause requestAnimationFrame callbacks in hidden tabs, so the pending frame never runs until the tab is visible again. Analytics is not visual work. Use a timer-based throttle or debounce (possibly with flush on visibilitychange or pagehide) for it, and keep rAF only for screen updates.
Exercise
In the first rafThrottle version, one throttled function is shared as a method by objects a and b. a.update(1) and b.update(2) are called in the same frame. What this and arguments does fn receive, and how does the second version fix it?
Show answer
The frame callback is an arrow function created during a.update(1), so fn receives this === a but lastArgs [2] from b's call. The second version stores lastThis on every call and applies fn with lastThis and lastArgs together, so fn receives this === b with [2].
Exercise
Write the teardown steps for a component that attached onMove = rafThrottle(...) to window's pointermove event, and explain why each step is needed.
Show answer
Call window.removeEventListener('pointermove', onMove) so no new events schedule frames, then call onMove.cancel() so a frame that is already queued does not run and write to DOM nodes that no longer exist. Cancel also drops the stored event object reference.