Javascript requestAnimationFrame()
You could says I live behind the rock in Javascript world in past two years. I recently developed Typing Mania in pure Javascript, decided to be my own replacement for Flash-based TypingMania Odyssey, which for some reason I can’t set it up properly at all.
Because I haven’t been following what happened in Javascript world recently, I did not know requestAnimationFrame()
exists. I use setInterval(func, 20)
as my main loop.
For some reason I decided against using canvas in this development – everything is composited from <img>
, <div>
and <p>
blocks with CSS formatting. At first this work quite well, until I start with decoration, labels and such, and as number of elements grows, performance dropped considerably (sometimes only 15fps during game play)
This is quite to my disappointment. I know the bottleneck is its DOM interface – the time need to add/remove/change all needed DOM elements is high. I even tried to minimized the number of DOM changes, but it did not get faster.
Then I try searching for solution again today, and viola, I found requestAnimationFrame()
. It works perfectly, delivering constant 60fps even for toughest songs session. I am happy.
I have been searching around, and I see that a lot of people said that requestAnimationFrame()
is not suitable for main game logic loop. Come one, people, you are seriously writing code that depends on loop running in constant time?
I have always structure my Game/GUI application as follow:
- Input are handled in input handler. Anything that depend on external data (i.e. network) are processed immediately, otherwise are queued for main thread or scheduled to be process in another thread.
- Logic are either processed by another thread or just before rendering process in main thread, but requiring deltaTime since last processing to fast-forward states correctly.
- Rendering is done in render loop. This reads data from various structs/class and composite the display.
This looks completely normal and structured to me. This also have no forwarding-delay/logic-breaks-because-deltaTime-is-different/etc. problems I see people warns about regarding requestAnimationFrame();