Is there a more accurate way to create a Javascript timer than setTimeout?

后端 未结 16 2240
礼貌的吻别
礼貌的吻别 2020-11-22 14:11

Something that has always bugged me is how unpredictable the setTimeout() method in Javascript is.

In my experience, the timer is horribly inaccurate in

16条回答
  •  再見小時候
    2020-11-22 14:53

    This is a timer I made for a music project of mine which does this thing. Timer that is accurate on all devices.

    var Timer = function(){
      var framebuffer = 0,
      var msSinceInitialized = 0,
      var timer = this;
    
      var timeAtLastInterval = new Date().getTime();
    
      setInterval(function(){
        var frametime = new Date().getTime();
        var timeElapsed = frametime - timeAtLastInterval;
        msSinceInitialized += timeElapsed;
        timeAtLastInterval = frametime;
      },1);
    
      this.setInterval = function(callback,timeout,arguments) {
        var timeStarted = msSinceInitialized;
        var interval = setInterval(function(){
          var totaltimepassed = msSinceInitialized - timeStarted;
          if (totaltimepassed >= timeout) {
            callback(arguments);
            timeStarted = msSinceInitialized;
          }
        },1);
    
        return interval;
      }
    }
    
    var timer = new Timer();
    timer.setInterval(function(){console.log("This timer will not drift."),1000}

提交回复
热议问题