Day 35

requestAnimationFrame

11 min
JavaScript 100 Days

requestAnimationFrame (rAF) browser ke animation frame se sync hota hai — 60fps par smooth animations ke liye yahi best way hai. setInterval se zyada efficient aur battery-friendly.

rAF Basics

requestAnimationFrame se animation loop chalao.

raf.js
javascript
let x = 0;
const box = document.getElementById("box");

function animate() {
  x += 2;
  box.style.transform = `translateX(${x}px)`;
  
  if (x < 400) {
    requestAnimationFrame(animate); // next frame
  }
}

requestAnimationFrame(animate); // start!

Cancel Animation

cancelAnimationFrame se animation rok sakte hain.

cancel.js
javascript
let rafId;
let angle = 0;

function rotate() {
  angle += 1;
  element.style.transform = `rotate(${angle}deg)`;
  rafId = requestAnimationFrame(rotate);
}

// Start
rafId = requestAnimationFrame(rotate);

// Stop after 2 seconds
setTimeout(() => cancelAnimationFrame(rafId), 2000);

🎯 Practice Challenge

Canvas par ek bouncing ball banao using requestAnimationFrame. Ball walls se bounce kare.