Search code examples
javascriptsetintervalframe-rate

Run function at 60fps


I'm currently using setInterval( () => {}, 16 ) to run my code 60fps, but this makes the code run at 62.5fps, which makes the game movements jump forward twice the speed for a few frames per second. Using interval 17 makes the game movement freeze for a frame every once in a while.

How can I run the code truly at 60fps for maximum smoothness?


Solution

  • use Window.requestAnimationFrame([callback])

    That way your application will be called when it's time to render, wether the monitor is 30hz, 60hz or 120hz or more.

    See this example from https://css-tricks.com/using-requestanimationframe/ on how to use it if the MDN documentation isn't clear enough.

    var globalID;
    
    function repeatOften() {
      $("<div />").appendTo("body");
      globalID = requestAnimationFrame(repeatOften);
    }
    
      globalID = requestAnimationFrame(repeatOften);
    
    $("#stop").on("click", function() {
      cancelAnimationFrame(globalID);
    });
    $("#start").on("click", function() {
      globalID = requestAnimationFrame(repeatOften);
    });
    div {
      width: 10px;
      height: 10px;
      background: orange;
      float: left;
    }
    
    button {
      position: absolute;
      top: 20px;
      left: 20px;
    }
    #stop {
      left: 100px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button id="start">start</button>
    <button id="stop">stop</button>