Skip to content
the poor coder

setTimeout vs requestAnimationFrame

Poor Man
Published
Reading time
1 min read
On this page

setTimeout vs requestAnimationFrame#

When it comes to creating animations and running code at intervals, two popular methods are setTimeout and requestAnimationFrame. Both of these methods can be used to execute code after a certain amount of time has passed, but there are some important differences to consider.

setTimeout#

setTimeout is a method that allows you to execute a function after a certain amount of time has passed. You can specify the amount of time in milliseconds using the first argument, and the function to execute using the second argument.

Text

setTimeout(function() {
  // code to execute after 1000ms (1 second)
}, 1000);

One important thing to note is that setTimeout is not guaranteed to run at the exact time you specify. The actual time may vary depending on factors such as browser performance and other running processes on the device. This can cause issues with smooth animations, especially if you are trying to update the screen at a consistent rate.

requestAnimationFrame#

requestAnimationFrame is a newer method that was introduced specifically for creating smooth and efficient animations. It works by scheduling a function to run before the next repaint of the screen, which ensures that the animation is synchronized with the device's refresh rate.

Text

requestAnimationFrame(function() {
  // code to execute before next repaint
});

In addition to providing smoother animations, requestAnimationFrame also helps reduce CPU usage by only running the animation when the tab is visible in the browser. This can help improve battery life and prevent unnecessary strain on the device.

Conclusion#

Overall, requestAnimationFrame is generally preferred for creating smooth and efficient animations. However, setTimeout can still be useful in some cases, such as when you need to run code at a specific time interval or when you need to add a delay to a function call. It's important to consider the specific needs of your project when deciding which method to use.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC