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.
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]]);
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]);
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"]);
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]]);
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]]);
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();
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]]);
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).
I'm here to help with Throttle to animation frames. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.