修复setInterval每次定时执行的偏差,适用于倒计时场景
发布于 2 年前 作者 otang 1822 次浏览 来自 分享
/** interval.js**/
/**
* 小程序内用法:
* var interval=require("../../core/js/interval");
* this.stepTimer=new interval.SetInterval(()=>{},1000);
* 清除定时器:this.stepTimer.clear();
**/
/**
 * callback: 每次回调执行函数
 * time: 每隔多少时间回调一次
 */
function SetInterval(callback, time{
  let that=this;
  this.start = new Date().getTime();
  this.end;
  this.offset;
  this.loopNum = 0;
  this.timeoutTag = null;
  this.time = time;
  this.callback = callback;
  this.set(time);
  this.clear=function(){
    clearTimeout(that.timeoutTag);
    that.timeoutTag = undefined;
    console.log("清除定时器----")
  }
}
SetInterval.prototype.set = function (_time{
  var that = this;
  if (this.timeoutTag === undefinedreturn;
  clearTimeout(this.timeoutTag);
  this.timeoutTag = null;
  that.timeoutTag = setTimeout(function () {
    that.loopNum++;
    that.end = new Date().getTime();
    that.callback();
    that.offset = that.end - that.start - that.time * that.loopNum;
    // console.log("偏移了----" + that.offset);
    if (that.offset > 0) {
      that.set(that.time - that.offset);
    } else if (that.offset < 0) {
      that.set(that.time + that.offset);
    } else {
      that.set(that.time);
    }
  }, _time);
};
module.exports={
  SetInterval,
}
回到顶部