减少/限制 Canvas 动画的 requestAnimationFrame

reduce / thottle requestAnimationFrame for Canvas animation

我正在创建一个 HTML5 Canvas 动画并希望降低/限制帧速率。我目前正在使用 requestAnimationFrame 方法。为了限制帧速率,我使用 setTimeout。

是否有更好/更有效的方法来做到这一点?

// Game - animation loop 
      var fps = 5;
      function step() {
        setTimeout(function() {
          update();
          draw();
          window.requestAnimationFrame(step);
        }, 1000 / fps);
      }

谢谢

const fps = 5;
const delay = Math.ceil(1000 / fps);
let last = Date.now();
let now;

function step () {
    now = Date.now();
    if(now - last < delay) {
        return requestAnimationFrame(step);
    }
    last = now;
    update();
    draw();
    requestAnimationFrame(step);
}

step();