Hacker News new | ask | show | jobs
by tomxor 1761 days ago
> there's no reason to do that every N milliseconds

Usually if you want to do any kind of posteriori procedural animation i.e real-time physics, you need a constant interval, and RAF does not give you this...

RAF usually runs at 60FPS but it can drop to 30 or increase to 120 depending on the browser, hardware and power saving modes - Which means whatever you are running in that function can get called at drastically different intervals for different users.

In this case the animation is a priori, meaning we don't have to simulate intermediate steps, so it's possible to correct for this inside the RAF alone by using Date.now() as the time parameter for shifting the sine wave... however this is not always the case. And in those cases setInterval can be far simpler when timing is important, but if you want to continue using RAF ultimately you would need to decouple rendering from "physics" or any timing related code that cannot be calculated a priori, and run the latter at a constant interval.

1 comments

I think a few topics are conflated here. The part of the code that draws pixels into a canvas (or tells webgl to draw) should always be called from RAF - there's never a reason to do that more often than the screen refreshes. And since TFA does basically nothing except set canvas pixels, RAF is clearly the thing to use.

OTOH whether you want your animation to advance in real time is a separate issue, regardless of whether the animation is interpolated. If you do want real-time animations, and you're using an interpolated physics engine or similar, there really aren't any good options besides decoupling the interpolation from the rendering. And if you've done that, then it doesn't matter much whether the interpolation is called from RAF or setInterval (personally I use both, so that physics ticks can happen between RAF events if the CPU load is heavy).

But as a footnote, setInterval definitely does not give you a "constant" interval. Besides the normal variance, browsers will throttle the events (e.g. if the document is in a background tab).

Nothing gives you a constant interval, but it attempts to unlike RAF.