Skip to content

Use requestAnimationFrame instead of setInterval for the game loop #6

@andreban

Description

@andreban

requestAnimationFrame() (rAF) is a more performant and precise alternative to setInterval() run animation loops in JavaScript that is well supported across browsers. This talk has more details on why that is the case.

Switching the code to rAF should be straightforward:

  1. In the render member of the game data, declare a variable to track the last game update and another for the target delay between frames (1000 ms divided by the target FPS).
    render: {
        lastUpdate: null,
        frameInterval: 1000 / 30, // 30 FPS
    },

Then, change the main loop to use rAF. Whenever rAF is called before an update is due, skip the rendering code.

/**
 * Main loop
 */
function main() {
    const render = (timestamp) => {
        // If this is the first frame, or frameInterval has passed, render the frame.
        if (!data.render.lastUpdate ||
                (timestamp - data.render.lastUpdate > data.render.frameInterval)) {
            clearScreen();
            rayCasting();
            data.render.lastUpdate = timestamp;
        }

        // Schedule the next frame to be rendered.
        requestAnimationFrame(render);
    };
    requestAnimationFrame(render);
}

Let me know if this makes sense to you, and I'll be happy to write a pull request updating the code and tutorials.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions