Reputation: 2583
I'm making a little game using <canvas>
with JS/Coffeescript.
As of now, my draw loop is done using requestAnimationFrame:
draw: () =>
# Various drawing code.
requestAnimFrame(@draw, @canvas)
While my update loop is on a simple setInterval
:
setInterval(() => @update Date.now(), 1000/FPS)
I separated them so that the drawing doesn't get clogged up with unrelated update code, thinking this is probably the proper way.
But is it? Does it make sense? How do I ensure smooth animations at minimal cost to systems?
Upvotes: 0
Views: 847
Reputation:
Using both requestAnimationFrame
(rAF) and setInterval
will only create an extra overhead.
This is because JavaScript is single-threaded and has to execute scopes one by one. If JS engine is inside the scope for rAF then the execution of the scope for setInterval is queued up as an event that is executed after rAF has exited current scope - or vice verse. And the code can still get clogged up/stacked (due to setInterval
).
So no benefit there, quite the contrary as there is more code to execute (more is sometimes less, but not in this case) incl. internal stack pushing and popping, creation and queuing of event, extra code to parse etc. - perhaps at a microscopic level, but it your code is expensive then it may matter. That being said, consider using 30 fps instead of 60 fps, which is plenty in most cases and it about doubles your budget.
With rAF you have a "time budget" typically about 16.7 ms. No matter what you do you will have to get your code needed to create a single frame to execute within that time frame. If not a frame (or more) will be skipped.
The key is to optimize the code and how you put together your scene, literally as well as abstract. Cache everything you can (memory is your friend), update only what is needed and so forth. There is no generic answer for this as it depends from case to case what is the optimal way of doing things.
Upvotes: 1