Skip to the code

Throttle to animation frames

The tea shop's menu moves a "Back to top" button as the page scrolls, and a tea photo follows the pointer when you hover over it. Their handlers only need to run as often as the screen can show the result: once per frame. Write rafThrottle(fn), which returns a function that runs fn at most once per animation frame, with the latest call's arguments.

The first call asks for an animation frame with requestAnimationFrame, and calls before that frame only replace the this and arguments it will use. In the frame, call fn once, with the latest call's this and arguments. A call made after that, including one made from inside fn, asks for the next frame. The returned function returns nothing. It has a cancel() method, which cancels the frame that's waiting, with cancelAnimationFrame, and forgets the arguments; calls after cancel() work as before.

The JavaScript problem Throttle (throttle) limits a function by time, with a wait in milliseconds. A frame-based throttle fits scroll and pointer handlers better. It runs right before the browser renders, so every update is in the next frame and none is thrown away. Its rate follows the screen, 60 times a second on one and 120 on another. It turns every event of a frame into one run, even when several kinds of events (scroll, resize, pointermove) feed one handler. And browsers pause animation frames in background tabs, so it does nothing while nobody's looking.

const follow = rafThrottle((x, y) => (photo.style.transform = "translate(" + x + "px, " + y + "px)"));
photo.addEventListener("pointermove", (event) => follow(event.offsetX, event.offsetY));
// However many pointer events arrive between two frames, the photo moves once per frame, to the latest spot.

What the tests check

  1. runs fn once, in the next frame, with the latest arguments
    const clock = useFakeTimers();
    const seen = [];
    const onScroll = rafThrottle((y) => seen.push([y, clock.now()]));
    onScroll(10);
    onScroll(40);
    onScroll(90);
    expect(seen).toEqual([]);
    await clock.runAllAsync();
    expect(seen).toEqual([[90, 16]]);
    
  2. asks for one frame however many calls come before it
    const clock = useFakeTimers();
    let frames = 0;
    const realFrame = requestAnimationFrame;
    globalThis.requestAnimationFrame = (callback) => {
      frames += 1;
      return realFrame(callback);
    };
    const fn = spy();
    const throttled = rafThrottle(fn);
    for (let index = 0; index < 20; index++) throttled(index);
    await clock.runAllAsync();
    expect(frames).toBe(1);
    expect(fn.callCount).toBe(1);
    expect(fn.calls[0].args).toEqual([19]);
    
  3. passes the latest call's this and every argument
    const clock = useFakeTimers();
    const fn = spy();
    const throttled = rafThrottle(fn);
    const first = { name: "first" };
    const second = { name: "second" };
    throttled.call(first, "a");
    throttled.call(second, "b", "c");
    await clock.runAllAsync();
    expect(fn.callCount).toBe(1);
    expect(fn.calls[0].this).toBe(second);
    expect(fn.calls[0].args).toEqual(["b", "c"]);
    
  4. a call after the frame waits for the next one
    const clock = useFakeTimers();
    const seen = [];
    const throttled = rafThrottle((value) => seen.push([value, clock.now()]));
    throttled("green");
    clock.tick(16);
    throttled("mint");
    expect(seen).toEqual([["green", 16]]);
    clock.tick(16);
    expect(seen).toEqual([["green", 16], ["mint", 32]]);
    
  5. a call from inside fn goes to the next frame
    const clock = useFakeTimers();
    const seen = [];
    const throttled = rafThrottle((step) => {
      seen.push([step, clock.now()]);
      if (step < 3) throttled(step + 1);
    });
    throttled(1);
    await clock.runAllAsync();
    expect(seen).toEqual([[1, 16], [2, 32], [3, 48]]);
    
  6. cancel() drops the waiting call, and calls after it work
    const clock = useFakeTimers();
    const seen = [];
    const throttled = rafThrottle((value) => seen.push([value, clock.now()]));
    throttled("green");
    throttled.cancel();
    await clock.runAllAsync();
    expect(seen).toEqual([]);
    throttled("oolong");
    await clock.runAllAsync();
    expect(seen).toEqual([["oolong", 32]]);
    throttled.cancel();
    
  7. nothing runs while the page is hidden, and the latest call runs when it's visible
    const clock = useFakeTimers();
    const seen = [];
    const throttled = rafThrottle((value) => seen.push([value, clock.now()]));
    setVisibility("hidden");
    throttled(1);
    throttled(2);
    clock.tick(1000);
    await clock.runAllAsync();
    expect(seen).toEqual([]);
    setVisibility("visible");
    await clock.runAllAsync();
    expect(seen).toEqual([[2, 1008]]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).