定時器類
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