nluqo / broughlike-tutorial

MIT License
55 stars 12 forks source link

Replace setInterval with requestAnimationFrame #6

Open spillz opened 2 years ago

spillz commented 2 years ago

Hi! I used the BroughLike code as a base for a recent game jam as a way to teach myself JS. Excellent tutorial and I ended up with a graphically intensive platformer. Was getting some weird performance issues on Chromebook that I have isolated to the use of setInterval. It seems that if the device can't keep up with the requested frame rate, it stacks up too many draw calls and breaks the renderer, causing freezes and occasional reboots. I suspect the severity of this issue is device specific but it does highlight the limitations of setInterval for game animation.

requestAnimationFrame solves this issue by only queuing updates up to the monitor refresh rate or below that if the scene is too intense for the hardware. It's a relatively straightforward change but ideally you should also track the time delta to keep animation consistent across frame rates[1]. It also helps make animations smoother because the frame updates exactly line up with rendering.

setInterval will probably work for 99% of users but requestAnimationFrame does seem to be the best practice for frame updates.

[1] see https://blog.webdevsimplified.com/2021-12/request-animation-frame/

nluqo commented 2 years ago

You're right, requestAnimationFrame is the best practice. I left it out because, and this might seem silly, it requires one extra line because you have to call it again in the handler. Maybe adding a note about it might be the best.

Glad the tutorial helped and surprised you ended up with a platformer. That's cool.