← Back tothis vs that

setTimeout(0) vs requestAnimationFrame

Written byPhuoc Nguyen
Created
13 Dec, 2023
Category
JavaScript
When it comes to optimizing web development performance, developers have many tools and techniques at their disposal to ensure their code runs efficiently. Two popular tools are `setTimeout(0)` and `requestAnimationFrame`. Although they both delay running a block of code until the next animation frame, they function differently.
In this post, we'll compare `setTimeout(0)` and `requestAnimationFrame` to help you understand their differences and how to use them effectively.

setTimeout(0)

`setTimeout(0)` is a method that's often used to delay the execution of a block of code until the next tick of the event loop. This is helpful when you need to "defer" code so it runs after other important code has finished executing.
It's important to remember that `setTimeout(0)` won't necessarily run immediately. It'll run as soon as the current code block has finished executing and the event loop is ready to execute the next block of code. This means that if there's a lot of code running at the same time, `setTimeout(0)` may be delayed by more important code.
You can use `setTimeout(0)` to defer the execution of code that's not immediately necessary, but may become necessary later on. For example, if you have a function that updates the UI, but it's not critical that it runs immediately, you can use `setTimeout(0)` to make sure it runs after more important code.

requestAnimationFrame

`requestAnimationFrame` is a method introduced with HTML5 that's perfect for creating smooth animations. By calling the specified function right before the next repaint in an animation loop, it ensures smooth and jitters-free animation.
`requestAnimationFrame` is executed before the next “render” loop iteration instead of the event loop. However, it only works when the browser is ready to render a new frame, which means it won't run if the tab is inactive or if the user is scrolling. `requestAnimationFrame` also automatically syncs with the display refresh rate, making it an excellent choice for animation-related code.
To demonstrate how `requestAnimationFrame` can be used for timing and measuring performance, the sample code below runs a loop that increments the `count` variable every time it runs, using `requestAnimationFrame`. The loop continues running until the current time minus the start time is greater than or equal to 5000 milliseconds. At that point, it logs how many times the loop ran in the last five seconds.
js
let count = 0;
const start = Date.now();
const loop = () => {
count += 1;
(Date.now() - start < 5000)
? requestAnimationFrame(loop)
: console.log(`${count} loops run in 5 seconds`);
};
requestAnimationFrame(loop);
The code sample produces the following output:
js
301 loops run in 5 seconds
Based on the data, it appears that the loop ran 301 times in just five seconds, which is comparable to 60 frames per second.
Now, let's explore a code snippet that utilizes `requestAnimationFrame` to produce seamless animations:
js
const animate = (timestamp) => {
// Code to update animation state
requestAnimationFrame(animate);
};

// Start the animation loop
requestAnimationFrame(animate);
In this example, the `requestAnimationFrame` function is used to repeatedly call the `animate()` function. This function updates the animation state and renders it on each frame. By passing the `timestamp` argument to `animate()`, we can calculate the time elapsed between frames and adjust the animation accordingly.

Conclusion

To sum up, `requestAnimationFrame` and `setTimeout(0)` are both handy tools for delaying code execution until the next animation frame or event loop tick. Although they may appear similar, they function differently and have distinct use cases.
If you're working with animation-related code and want to ensure smooth animation, `requestAnimationFrame` is the way to go.
However, if you want to hold off executing a block of code until after other code has finished running, `setTimeout(0)` is the better option. Knowing the differences between these two methods will help you write more efficient and effective code.

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn