Loading

js 实现定时器的开启与暂停功能

定时器类

class myTimer {
  /**
   * @param {Function} cb 回调函数
   * @param {Number} sec 执行间隔时间ms
   */
  constructor(cb, sec) {
    this.cb = cb;
    this.timer = null;
    this.sec = sec;
  }
  /**
   * 运行
   */
  run() {
    this.timer = setInterval(this.cb, this.sec);
  }
  /**
   * 暂停
   */
  stop() {
    clearInterval(this.timer);
    this.timer = null;
  }
}

测试

使用场景:多用于页面倒计时

let count = 10;
let timer = new myTimer(() => {
  // 达到条件,停止定时器,并清空当前引用,释放内存
  if (count < 3) {
    timer.stop();
    timer = null;
  } else {
    count--;
    console.log(count);
  }
}, 1000);

timer.run();
// 10
// 9
// ...
// 3
timer.stop();
timer.run();
// 2
timer.run(); // 此时内存已被释放,定时器的对象应用被清除
// Uncaught TypeError: Cannot read property 'run' of null
posted @ 2021-05-22 16:54  Frank-Link  阅读(5128)  评论(0编辑  收藏  举报