Open In App

SetTimeout VS RequestAnimationFrame

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The setTimeout and requestAnimationFrame are functions that can be used to execute code after a delay. However, they serve different purposes and are optimized for different scenarios, especially when it comes to animations and performance.

What is setTimeout?

setTimeout is a built-in JavaScript function that allows scheduling the execution of a function or code snippet after a specified delay, which is measured in milliseconds. This function is commonly used for:

  • Delaying the execution of the code
  • Implementing simple animations
  • Scheduling tasks to run in the future

Syntax

setTimeout(function, delay);

Example: This illustrates the execution of a function to log a message after a delay of 2 seconds.

JavaScript
setTimeout(function() {
    console.log('Delayed function executed.');
}, 2000);

Output

Delayed function executed.

What is requestAnimationFrame?

The requestAnimationFrame is a method offered by the browser's rendering engine that helps optimize animations and visual updates, and it schedules a function to be executed just before the browser's next repaint, typically in sync with the screen's refresh rate. This method is specifically designed to create smooth and efficient animations on the web.

Syntax

requestAnimationFrame(callback);

Example: This demonstrates and invokes a function called "animate" that logs "Animating..." continuously using requestAnimationFrame for smooth animations.

JavaScript
function animate() {
    console.log('Animating...');
    requestAnimationFrame(animate);
}
animate();

Output

Animating...

Difference Between SetTimeout and RequestAnimationFrame

Characteristics

SetTimeout

RequestAnimationFrame

Purpose

The General-purpose delayed execution

The Optimized for the smooth animations and visual updates

Timing

Inaccurate may drift over time

Synchronized with the browser's repaint cycle

Frame Rate

Not tied to the screen refresh rate

Tied to the screen refresh rate

Battery and Performance

Can be less efficient for the animations

The Optimized for the battery and performance

Usage

The Simple animations, delays and non-visual tasks

The Complex animations and visual updates

Browser Support

The Supported in the all browsers

The Supported in the modern browsers


Next Article
Article Tags :

Similar Reads