手写计时器类

162 阅读1分钟

业务需求总是会用到计时器,比如获取验证码、轮播、定时任务等,每次都去写一大堆代码,就很***,所以就封装了一个计时器类,以后就可以直接new了

用法

创建一个计时器实例,传入2个参数:回调函数(用来获取计时器运行了多长时间)、倒计时时间(s),提供了4个方法:启动,暂停,继续,结束。

// 创建一个计时器实例
const timer = new Timer((elapsedTime) => {
    console.log("已运行了:" + elapsedTime + "s")
}, 5);

// 启动计时器
timer.start();

// 暂停计时器
timer.pause();

// 继续计时器
timer.resume();

// 停止计时器
timer.stop();

代码

class Timer {
  constructor(callback, interval = 30) {
    this.timerId = null;
    this.startTime = null;
    this.elapsedTime = 0;
    this.isRunning = false;
    this.callback = callback;
    this.interval = interval;
  }

  start() {
    if (!this.isRunning) {
      // 记录开始时间
      this.startTime = Date.now() - this.elapsedTime;
      this.isRunning = true;
      this._run();
    }
  }

  pause() {
    if (this.isRunning) {
      clearInterval(this.timerId);
      this.timerId = null;
      // 暂停时 记录倒计时进行了多少时间
      this.elapsedTime = Date.now() - this.startTime;
      this.isRunning = false;
    }
  }

  resume() {
    if (!this.isRunning) {
      // 继续时 重置开始时间 (当前时间-暂停前运行的时间)
      this.startTime = Date.now() - this.elapsedTime;
      this.isRunning = true;
      this._run();
    }
  }

  stop() {
    if (this.isRunning) {
      clearInterval(this.timerId);
      this.timerId = null;
      this.elapsedTime = 0;
      this.isRunning = false;
    }
  }

  _run() {
    this.timerId = setInterval(() => {
      // 计算计时器跑了多长时间
      this.elapsedTime = Date.now() - this.startTime;

      // 返回倒计时剩余时间
      // this.callback(this.interval - Math.floor(this.elapsedTime / 1000));
      // 返回倒计时运行了多少时间
      this.callback(Math.floor(this.elapsedTime / 1000));

      if (this.elapsedTime >= this.interval * 1000) {
        this.stop();
      }
    }, 1000);
  }
}