requestAnimationFrame at a limited framerate

前端 未结 3 1210
梦毁少年i
梦毁少年i 2020-12-30 04:16

As I understand it, usage of the JS requestAnimationFrame API is intended for cases where the framerate isn\'t in need of being controlled, but I have a use cas

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 05:11

    This is just a proof of concept.

    All we do is set our frames per second and intervals between each frame. In the drawing function we deduct our last frame’s execution time from the current time to check whether the time elapsed since the last frame is more than our interval (which is based on the fps) or not. If the condition evaluates to true, we set the time for our current frame which is going to be the “last frame execution time” in the next drawing call.

    var Timer = function(callback, fps){
      var now = 0;
      var delta = 0;
      var then = Date.now();
    
      var frames = 0;
      var oldtime = 0;
    
      fps = 1000 / (this.fps || fps || 60);
    
      return requestAnimationFrame(function loop(time){
        requestAnimationFrame(loop);
    
        now = Date.now();
        delta = now - then;
    
        if (delta > fps) {
          // Update time stuffs
          then = now - (delta % fps);
    
          // Calculate the frames per second.
          frames = 1000 / (time - oldtime)
          oldtime = time;
    
          // Call the callback-function and pass
          // our current frame into it.
          callback(frames);
        }
      });
    };
    

    Usage:

    var set;
    document.onclick = function(){
      set = true;
    };
    
    Timer(function(fps){
      if(set) this.fps = 30;
      console.log(fps);
    }, 5);
    

    http://jsfiddle.net/ARTsinn/rPAeN/

提交回复
热议问题