秒表计时器(Timeout 实现 Interval)

问题:setInterval 定时器不准确

解决:

const timerIdList = {};

mySetInterval(fn: (time: number) => void, delay: number) {
  const key = Symbol();
  const interval = () => {
    const start = Date.now();
    this.timerIdList[key] = setTimeout(() => {
      const end = Date.now();
      const excuTime = end - start;
      try {
        fn(excuTime);
      } catch (e) {
        throw e.toString();
      }
      interval();
    }, 1000, false);
  };
  setTimeout(interval, delay);
  return key;
}

myClearInterval(key: symbol) {
  if (key in this.timerIdList) {
    clearTimeout(this.timerIdList[key]);
    delete this.timerIdList[key];
  }
}

使用:

// 设定
const id = this.mySetInterval((time) => {
  console.log(time);
  this.time += time; // 准确时间戳返回
})

// 清除
this.myClearInterval(id);

版权声明:本文为lucky541788原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。