A real rAF loop: painted frames vs your loop’s updates, delta-time, pauses and cleanup. rAF or setInterval: which suits animation, and why? An interactive…
Why it matters
rAF and delta-time are the base of smooth animation: games, canvas, scroll effects, physics. Knowing "one update per frame, movement per second" gives animation that runs at the same speed on every screen, saves battery and does not stutter, unlike setInterval.
The key idea
rAF follows the screen’s frames, delta-time makes speed follow time
Common mistakes
The animation runs faster on a 120Hz screen than on a 60Hz one A sign that movement is px per frame without dt. Multiply by dt so the speed is per second, the same at every FPS.
Animation with setInterval stutters and wastes battery A timer is not in step with frames: some frames are skipped, some work is wasted, and it keeps running in a background tab. rAF follows the frames and stops by itself in a hidden tab.
The loop runs on after the component is gone A missing cancelAnimationFrame. Keep the id from each requestAnimationFrame and cancel it in the cleanup (return () => cancelAnimationFrame(id)). Otherwise every remount adds one more loop.
The ball teleports after a pause or a tab switchdt is counted from an old last. Cap it: dt = Math.min(dt, 0.1), or reset last on resume.
Try it in this playground
Switch the schedule to setInterval Watch the two strips on the board: the updates drift from the frames. Some frames get none, some get two.
Move per frame + a 20ms load The FPS drops and the ball slows with it. Switch to × dt: the FPS is still low, but the speed comes back.
Switch to another tab for a while, then come back While hidden, rAF is not called at all, while timers keep running (slowed down).
Turn the clamp off, Pause 2 seconds, Resume The first update gets a 2-second dt: the ball jumps hundreds of px.