Script Valley
JavaScript in the Browser: DOM, Events & APIs
Styles, Classes, and Layout via JavaScriptLesson 3.4

CSS transitions vs JavaScript animation: requestAnimationFrame

CSS transition, requestAnimationFrame, animation loop, cancelAnimationFrame, performance, reflow avoidance

CSS Transitions vs requestAnimationFrame

For state-change animations (open/close, hover effects), CSS transitions are the right tool โ€” they run on the compositor thread without touching JavaScript.

/* CSS */
.panel { height: 0; overflow: hidden; transition: height 0.3s ease; }
.panel.open { height: 200px; }

/* JS โ€” just toggle the class */
btn.addEventListener('click', () => panel.classList.toggle('open'));

requestAnimationFrame for JavaScript-Driven Animation

When animation logic must live in JavaScript (physics, canvas, data-driven), use requestAnimationFrame. The browser calls your callback once per frame just before painting โ€” synced to the display refresh rate.

let x = 0;
let animId;

function animate() {
  x += 2;
  box.style.transform = `translateX(${x}px)`;
  if (x < 300) animId = requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

// Stop it:
cancelAnimationFrame(animId);

Never use setInterval for animation โ€” it ignores the frame budget and causes jank. Batch all DOM reads before writes inside a single frame to avoid forced reflows.

Up next

Intersection Observer: detecting when elements enter the viewport

Sign in to track progress

CSS transitions vs JavaScript animation: requestAnimationFrame โ€” Styles, Classes, and Layout via JavaScript โ€” JavaScript in the Browser: DOM, Events & APIs โ€” Script Valley โ€” Script Valley