|
|
|
|
|
by fenomas
1769 days ago
|
|
requestAnimationFrame is much better here. If you're just drawing into a canvas, there's no reason to do that every N milliseconds - you want to do it once per screen refresh, which is what RAF is for. There's also the added benefit that RAF won't fire when the document isn't visible, so you don't waste cycles drawing to a canvas that's in a background tab, etc. |
|
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.