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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM