Global / Window

requestAnimationFrame

Tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint

Syntax

JavaScript
requestAnimationFrame(callback)

Parameters

ParameterTypeDescription
callback(timestamp: DOMHighResTimeStamp) => voidFunction called before the next repaint

Return Value

A long integer request ID that can be used with cancelAnimationFrame()

Examples

Basic Usage
function animate(timestamp: number) {
  // Update animation state
  console.log('Frame at', timestamp);
  requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Practical Example
function smoothScroll(target: number, duration: number) {
  const start = window.scrollY;
  const startTime = performance.now();
  function step(currentTime: number) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    window.scrollTo(0, start + (target - start) * progress);
    if (progress < 1) requestAnimationFrame(step);
  }
  requestAnimationFrame(step);
}
Advanced Usage
let frameId: number;
function startLoop() {
  frameId = requestAnimationFrame(function loop() {
    // render frame
    frameId = requestAnimationFrame(loop);
  });
}
function stopLoop() {
  cancelAnimationFrame(frameId);
}

Understanding requestAnimationFrame

The requestAnimationFrame method in JavaScript tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. It belongs to the window object and is one of the most widely used methods for working with window values in modern JavaScript and TypeScript applications.

The method signature is requestAnimationFrame(callback). It accepts 1 parameter: callback. When called, it returns a long integer request id that can be used with cancelanimationframe(). Understanding when and how to use requestAnimationFrame() helps you write more expressive, readable code.

Common use cases for requestAnimationFrame include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like window-settimeout, window-setinterval, enabling you to chain operations together for complex data manipulation pipelines.

Supported in all modern browsers. Available in Chrome, Firefox, Safari, Edge, and Node.js (via polyfill).

Browser Compatibility

Supported in all modern browsers. Available in Chrome, Firefox, Safari, Edge, and Node.js (via polyfill).

Related Methods

More Global / Window Methods

Other methods in the Global / Window object

Related Tools

More Global / Window Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.