setTimeout vs requestAnimationFrame

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.


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.


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe