JavaScript Interview Question #155

What is requestAnimationFrame()?

Performance, Browser APIs, Rendering & Modern Web Architecture Senior Advanced

Quick Interview Answer

requestAnimationFrame asks the browser to run a callback before a future repaint. It is designed for visual updates and animation work because the browser can coordinate callbacks with its rendering cycle.

Detailed Explanation

requestAnimationFrame asks the browser to run a callback before a future repaint. It is designed for visual updates and animation work because the browser can coordinate callbacks with its rendering cycle.

For smooth animations, update visual state in requestAnimationFrame rather than using fixed timers for every frame. The callback receives a high-resolution timestamp that can be used for time-based animation calculations.

Code Example

function animate(timestamp) {
    element.style.transform =
        `translateX(${timestamp / 20}px)`;

    requestAnimationFrame(animate);
}

const animationId =
    requestAnimationFrame(animate);

// cancelAnimationFrame(animationId);