freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #21 of 21

requestAnimationFrame · the render loop

NodetteVSThe Event Bubbler
Nodette saysrequestAnimationFrame schedules a callback before the next repaint — the right tool for animation.

requestAnimationFrame(fn) runs fn right before the browser paints (~60fps), passing a timestamp. Calling it again inside fn creates a smooth loop that pauses in background tabs (unlike setInterval). Use elapsed time, not a fixed step, so motion is frame-rate independent. cancelAnimationFrame(id) stops it.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleAnimate a box across the screen with a requestAnimationFrame loop.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;padding:20px"><div id="b" style="width:40px;height:40px;background:#b388ff"></div>
<script>let x=0;const b=document.getElementById('b');function loop(){x=(x+2)%300;b.style.transform='translateX('+x+'px)';requestAnimationFrame(loop);}loop();</script></body></html>
▶ Open the interactive comic issue
‹ Timing · SetTimeout · SetInterval · ClearTimeout