Tutorials Logic, IN info@tutorialslogic.com

Animations in JavaScript requestAnimationFrame

Browser Animation Model

Use Animations in JavaScript requestAnimationFrame when it clarifies browser behavior or runtime flow; prefer explicit values and visible console output over relying on implicit coercion or script order.

Animations

Animation should communicate a state change or relationship without delaying the user's task.

Animation Setup

Use a positioned container only when the animated element needs that coordinate system.

Initialize the visual start state before requesting the first frame.

Step 3:- Animations in JavaScript can be easily done by gradual changes in an element's style. The changes are called by a timer. Continuous JavaScript animations can be achieved by setting a tiny timer interval using the setInterval function.

Javascript Animations Worked Example

Javascript Animations Worked Example
<div id ="animation-container">
    <div id ="animation">JavaScript animation will go here</div>
</div>

Javascript Animations Worked Example 2

Javascript Animations Worked Example 2
#animation-container {
	width: 300px;
	height: 300px;
	position: relative;
	background: yellow;
}
#animation {
	width: 30px;
	height: 30px;
	position: absolute;
	background: red;
}

Javascript Animations Worked Example 3

Javascript Animations Worked Example 3
var id = null;
function animationMove() {
	var element = document.getElementById("animation");
	var loc = 0;
	clearInterval(id);
	id = setInterval(frame, 5);
	function frame() {
		if (loc == 350) {
			clearInterval(id);
		} else {
			loc++;
			element.style.top = loc + "px";
			element.style.left = loc + "px";
		}
	}
}

requestAnimationFrame

requestAnimationFrame is the preferred modern approach for animations. It syncs with the browser's repaint cycle (typically 60fps), resulting in smoother animations and better performance than setInterval.

requestAnimationFrame - JavaScript Example

requestAnimationFrame - JavaScript Example
const box = document.getElementById('animation');
let position = 0;
let animId;

function animate() {
  position += 2;
  box.style.left = position + 'px';

  if (position < 350) {
    animId = requestAnimationFrame(animate);
  } else {
    cancelAnimationFrame(animId);
    console.log('Animation complete');
  }
}

// Start
requestAnimationFrame(animate);

// Stop manually
// cancelAnimationFrame(animId);

CSS Transition Control

You can trigger CSS transitions by toggling classes with JavaScript - this is often the cleanest approach for simple animations.

CSS Transitions via JS

CSS Transitions via JS
/* CSS */
.box {
  width: 50px;
  height: 50px;
  background: #e74c3c;
  transition: transform 0.5s ease, opacity 0.5s ease;
}
.box.active {
  transform: translateX(300px) rotate(360deg);
  opacity: 0.5;
}

CSS Transitions via JavaScript

CSS Transitions via JavaScript
// JavaScript
const box = document.querySelector('.box');
const btn = document.getElementById('animateBtn');

btn.addEventListener('click', () => {
  box.classList.toggle('active');
});

// Listen for animation end
box.addEventListener('transitionend', () => {
  console.log('Transition finished');
});

Web Animations API

The Web Animations API provides a powerful JavaScript interface to control animations programmatically - including play, pause, reverse, and speed control.

Web Animations API - JavaScript Example

Web Animations API - JavaScript Example
const element = document.getElementById('animation');

// Keyframes
const keyframes = [
  { transform: 'translateX(0px)', opacity: 1 },
  { transform: 'translateX(300px)', opacity: 0.5 },
  { transform: 'translateX(0px)', opacity: 1 }
];

// Options
const options = {
  duration: 2000,   // 2 seconds
  iterations: 3,    // repeat 3 times
  easing: 'ease-in-out',
  fill: 'forwards'
};

const anim = element.animate(keyframes, options);

// Control
anim.pause();
anim.play();
anim.reverse();
anim.playbackRate = 2; // double speed

anim.onfinish = () => console.log('Animation done!');

Animation Tool Selection

Use a CSS transition for a change between two visual states and CSS keyframes for a declarative sequence. Use the Web Animations API when JavaScript must create keyframes, control playback, inspect timing, or coordinate several effects. Use `requestAnimationFrame` when each frame depends on simulation state, pointer input, canvas drawing, or calculations that cannot be expressed as keyframes.

Do not select JavaScript merely because the animation is dynamic. CSS custom properties, classes, and the Web Animations API can keep timing in the browser animation system while application code controls state. Conversely, forcing a physics simulation into many generated CSS keyframes can make interruption and interaction harder than a frame loop.

Animation should communicate hierarchy, continuity, cause, progress, or feedback. Decorative movement that delays work, competes with reading, or lacks a stable end state reduces usability. Define the state before, during, after, and when interrupted before choosing easing or duration.

Keep business state separate from visual interpolation. Completing a fade is not the same as saving a record, and a cancelled animation must not roll back a successful operation. The application should own the state transition; animation presents it and reports completion only when later UI behavior truly depends on that moment.

  • Choose CSS transitions for simple state changes.
  • Choose keyframes or Web Animations for declarative timelines.
  • Choose requestAnimationFrame for per-frame simulation or drawing.
  • Keep durable application state independent from visual progress.

Frame Timing and Lifecycle

`requestAnimationFrame` asks for one callback before a future repaint. The callback must request the next frame when work continues. Store the request ID and cancel it during teardown. Use `null` rather than zero as the inactive sentinel because request identifiers are opaque values whose numeric sequence must not be assumed.

Use the callback timestamp to calculate elapsed time. Advancing a fixed distance per callback makes movement faster on 120 Hz or 144 Hz displays than on 60 Hz displays. Clamp elapsed time after a long pause so physics or progress does not jump through boundaries when a background tab becomes visible again.

Most browsers pause animation-frame callbacks in background tabs and hidden iframes to save power. Observe `visibilitychange` when the application needs explicit pause and resume behavior. On resume, reset the previous timestamp or reconcile from an authoritative clock according to whether the animation represents decoration, media, a timer, or simulation.

Give every loop one owner. Repeated component mounts, route changes, or button clicks must not start overlapping loops unless that is intentional. Cancellation should remove listeners and observers associated with the animation as well as the next frame request. Make stop operations safe to call more than once.

  • Calculate progress from elapsed time, not frame count.
  • Cancel the stored request during teardown.
  • Define background-tab pause and resume semantics.
  • Prevent duplicate loops after repeated initialization.

Rendering Performance

A frame can include JavaScript, style calculation, layout, paint, and composition. Animating geometry such as width, height, margin, top, or left can trigger layout and paint. Transform and opacity changes can often be handled in composition, but browser optimization depends on the page and device; profile rather than promising that any property is always free.

Avoid layout thrashing by grouping DOM reads before writes. Reading geometry after changing layout-affecting styles can force the browser to calculate layout immediately, and repeating that pattern for many elements consumes the frame budget. Cache stable measurements and update all visual properties together where practical.

Do not add `will-change` broadly. Extra layers use memory and can worsen performance. Apply it only when measurements justify advance promotion and remove it when the effect ends. Large images, shadows, filters, blending, and many independently animated elements can remain expensive even when no layout occurs.

Use browser performance tools to inspect long animation frames, scripting, forced layout, paint, layer count, and dropped frames. Test low-powered mobile devices, high-refresh displays, zoom, and realistic content. An empty demonstration moving one square does not prove that a populated production view meets its responsiveness target.

  • Prefer transform and opacity when they match the visual requirement.
  • Batch layout reads before DOM writes.
  • Use compositor hints only after measurement.
  • Profile with production-sized content and target devices.

Accessibility and Testing

Respect `prefers-reduced-motion` for non-essential motion. Remove or replace large panning, scaling, parallax, and continuous effects when reduced motion is requested. A short opacity change may be a suitable alternative, but reduced does not mean every user accepts the same substitute. Essential status changes must remain understandable without movement.

Do not move keyboard focus unexpectedly, animate focus indicators away, or make controls chase the pointer. Keep hit targets stable while users interact. When content enters or leaves, manage focus and accessibility state from the semantic UI transition rather than from a visual completion callback that may not run under reduced motion.

Test start, pause, resume, reverse, cancel, rapid restart, component unmount, hidden-tab return, and reduced-motion behavior. For time-based code, inject a clock or call the frame-step function with known timestamps so tests are deterministic. Assert final state and cleanup instead of relying on screenshots taken after arbitrary sleeps.

Visual regression tests can catch a final layout but rarely prove smoothness. Combine them with performance traces, dropped-frame evidence, and interaction tests. Verify that cancellation leaves no pending request and that a user action during animation reaches a defined state rather than combining old and new transitions unpredictably.

  • Provide a reduced-motion path for non-essential effects.
  • Keep focus, controls, and hit targets stable.
  • Drive frame calculations with deterministic timestamps in tests.
  • Verify cancellation removes every pending animation resource.

Interpolation and Simulation

Normalize elapsed time into progress from zero to one, clamp it at both ends, and pass it through an easing function before interpolating the visual value. Keep the original start and end values stable throughout one run. Re-reading a changing start value every frame produces drift and makes reversal difficult to reason about.

Easing changes perceived acceleration, not the total business duration. Use linear progress for a constant-rate indicator, suitable ease-out motion for an element arriving, and spring or physics behavior only when overshoot communicates the interface well. Avoid custom curves that hold progress near zero so long that the control appears unresponsive.

A simulation may use a fixed update step for stable physics while rendering at the display cadence. Accumulate elapsed time, cap the amount processed after a pause, run a bounded number of updates, and interpolate the rendered state if needed. Without a cap, a slow frame can trigger a spiral of catch-up work that creates more slow frames.

When reversing or interrupting, begin from the currently rendered value and define velocity behavior. The Web Animations API can reverse or update playback rate for managed effects; a custom loop must preserve its own state. Test rapid toggles so two owners do not write competing transforms to the same element.

For scroll-linked effects, prefer platform scroll-driven animation support where available and design a static fallback. Avoid reading scroll position and writing layout repeatedly in an unthrottled listener. Test keyboard scrolling, zoom, reduced motion, content resizing, and restoration after browser navigation so the effect never hides information or blocks ordinary document movement.

  • Clamp normalized progress before applying easing.
  • Keep simulation updates bounded after long pauses.
  • Define interruption and reversal from the current visual state.
  • Allow one owner to write each animated property.
Before you move on

Animations in JavaScript requestAnimationFrame Mastery Check

5 checks
  • Choose an animation tool from timing, interaction, and lifecycle requirements.
  • Calculate frame progress from elapsed time on the animation clock.
  • Cancel frame requests and related listeners when the feature unmounts.
  • Step 3:- Animations in JavaScript can be easily done by gradual changes in an element's style.
  • The changes are called by a timer.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.