CodePark/ questions / Browser APIs
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Browser APIs

Why use requestAnimationFrame instead of setTimeout(fn, 16) for a JavaScript animation?

It runs right before the browser's next paint, matched to the display's refresh rate, and pauses in background tabs

requestAnimationFrame runs your callback right before the browser's next paint. So it matches the screen's refresh rate, including 120 Hz screens. You never do work for frames that are never shown. It also pauses in background tabs. setTimeout(fn, 16) drifts, can run in the middle of a frame, and keeps firing in hidden tabs.

"It runs the callback on a separate thread" is the tempting wrong answer. rAF still runs on the main thread. "It guarantees exactly 60 callbacks per second" is wrong, because it follows the device's refresh rate. "It runs before pending microtasks" is wrong, because microtasks always run before the browser moves on to rendering.