Search code examples
htmlwebglframerequestanimationframerate

How to lock FPS with requestAnimationFrame?


I used script from Paul Irish https://gist.github.com/paulirish/1579671 to create animation loop inside html site.

It works although it's faster in fullscreen mode than in browser window. Also, I observed different speeds depending on canvas size and depending on browser I use.

Question: How can I ensure stable frame rate using the script?

Code is available here (Beginning WebGL, chapter 1 by Brian Danchilla): https://github.com/bdanchilla/beginningwebgl/blob/master/01/2D_movement.html


Solution

  • Something like this should work. If the time delta between two frames is shorter than your FPS limit, the update function returns and waits for the next frame. But this will only limit the updates from happening too quickly; like emackey said, there's always the possibility the update loop will run more slowly.

    var updateId,
        previousDelta = 0,
        fpsLimit = 30;
    
    function update(currentDelta) {
        updateId = requestAnimationFrame(update);
    
        var delta = currentDelta - previousDelta;
    
        if (fpsLimit && delta < 1000 / fpsLimit) {
            return;
        }
    
        /* your code here */
    
        previousDelta = currentDelta;
    }