在項目中,常常需要使用定時器做一些輪詢的操作,Node JS裏面提供了兩個全局函數setTimeout
和setInterval
來實現,但是在使用中,定時任務往往是一些耗時操作,我們期望每一次輪詢等操作做完了在重新開始定時器,因此需要對定時器進行暫停和恢復,所以對定時器進行了一個簡單的封裝,代碼如下:
class CTimer {
/**
*
* @param {function} callback
* @param {number} interval ms
*/
constructor(callback, interval) {
this.state = 0;//0-stop 1-runing 2-pause
this.callback = callback;
this.interval = interval;
this.start();
}
start() {
if (this.state !== 1) {
this.timer = setInterval(this.callback, this.interval);
this.state = 1;
}
}
pause() {
if (this.state === 1) {
clearInterval(this.timer);
this.state = 2;
}
}
resume() {
if (this.state === 2) {
this.start();
}
}
stop() {
if (this.state !== 0) {
clearInterval(this.timer);
this.state = 0;
}
}
isStop() {
return (this.state === 0);
}
isRuning() {
return (this.state === 1);
}
isPaused() {
return (this.state === 2);
}
}
module.exports = CTimer;
上面的類的使用方法如下:
const CTimer=require('./ctimer');
let testTimer= new CTimer(async ()=>{
testTimer.pause();
await doSomething();
testTimer.resume();
},interval_ms);