Skip to content

Replace setInterval with requestAnimationFrame #6

@spillz

Description

@spillz

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/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions