What are the differences between setInterval x requestAnimationFrame?

Asked

Viewed 53 times

3

I am creating an application where I need to check if an X element was created on the page and thus take some actions. To make that check, I’m using the setInterval.

A few minutes ago, I remembered there’s a function requestAnimationFrame, commonly used to create games. I also remembered that this function is much faster, or rather more "fluid" apparently than the setInterval.

So I kept thinking. Which of these two functions is the best? What are the disadvantages and advantages of each of them?

Why don’t we just use requestAnimationFrame when we don’t need to define a waiting time since it has apparently a better performance? Also, if this function is really better, why not create a parameter to spend a waiting time and so replace the function setInterval?

Now back to the main question: what is the difference between the function requestAnimationFrame and the function setInterval in an in-depth way?

  • 1

    Another fundamental difference is that requestAnimationFrame does not execute callback if the active browser tab is not that of the application or the browser is minimized

1 answer

3


The function requestAnimationFrame() and the function setInterval() do completely different things.

The function setInterval() configures a timer (stopwatch) and executes a function or a code snippet when this timer expires. Using setInterval(), the developer can have the browser perform an action every X milliseconds.

Already the requestAnimationFrame() speaks to the browser that wants to perform an animation and asks the browser to call a specific function to update an animation frame before the next one repaint (repintura).

Note that in requestAnimationFrame() the developer cannot configure a time interval, because the moment when the next screen redesign will occur depends on the browser. It’s a developer’s way of saying "browser, when you’re redesigning the screen, perform these actions, draw that as well".

When building games, it is common to use both functions to perform different tasks. For example, the developer can create a function to draw something on the screen and use requestAnimationFrame() to call this function at the right time. Thus, the drawing will be done at the ideal time, efficiently.

On the other hand, the developer can update the game information on background, using the setInterval() or the setTimeout(), regardless of what is being displayed on the screen. Thus, when it is time to draw on the screen, the information will already be pre-processed.

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.