11.2. Write setTimeout with requestAnimationFrame
Topics
This question is in
11. TimersrequestAnimationFrame(callback) runs a callback once, just before the browser paints the next frame, roughly every 16 ms on a 60 Hz screen. It knows nothing about delays. Yet a "timeout made of frames" is useful: work scheduled this way runs in step with painting, and it naturally stops while the tab is hidden, because hidden tabs do not paint. Animation libraries and games time their delays this way.
Write rafTimeout(callback, delay, ...args) and clearRafTimeout(id) in raf-timeout.js, using only requestAnimationFrame and cancelAnimationFrame: no setTimeout, no setInterval.
Signature
function rafTimeout(callback, delay, ...args) // returns an id
function clearRafTimeout(id) // returns undefinedcallback: the function to run.delay: milliseconds to wait; missing,0or negative means "the next frame".args: passed tocallback.rafTimeoutreturns an id thatclearRafTimeoutaccepts, valid until the callback has run.
Requirements
- The callback never runs during the call to
rafTimeout, even withdelay0. - It runs on the first frame at which at least
delayms have passed since the call (measured withperformance.now()or the frame's timestamp), never on an earlier frame. - It counts time, not frames: frames can come at any spacing, from 1 ms to several seconds apart.
- It runs exactly once, with the extra arguments, and afterwards no frame is requested for it any more.
clearRafTimeout(id)before the callback runs stops it for good, however many frames have already passed, and no frame stays requested for it.- Each call returns a different id; clearing one timeout leaves the others alone.
- Clearing a timeout from inside another callback in the same frame still stops it.
- Clearing an unknown id, or one that has already run, does nothing and does not throw.
- A timeout started inside a frame callback measures its delay from the moment it was started.
Examples
// Frames every 16 ms:
rafTimeout(() => console.log("go"), 100);
// frames at 16, 32, 48, 64, 80, 96 ms: not yet
// frame at 112 ms: "go" (the first frame at least 100 ms after the call)const id = rafTimeout(console.log, 500, "a", "b");
clearRafTimeout(id); // nothing is ever printed
clearRafTimeout(id); // fine: already cleared
clearRafTimeout(999); // fine: unknown idrafTimeout(() => console.log("next frame")); // missing delay: the next frame, not now
console.log("now");
// "now", then "next frame" when the browser draws its next frameEnvironment
- Plain JavaScript in a browser page; the tests call the globals
rafTimeoutandclearRafTimeoutfromraf-timeout.js. - The tests replace
requestAnimationFrameandcancelAnimationFramewith a fake that draws a frame whenever the test says so, and replaceperformance.now()with a virtual clock. CallingsetTimeoutorsetIntervalmakes a test fail. - A callback that is added during a frame runs on the next frame, as in a real browser.
Hints
- A frame callback runs once. How does your code get to look at the next frame, and the one after?
requestAnimationFramereturns a new id every time you call it. Can that id be the one you give back to the caller?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it