Node.JS实现定时器暂停恢复

在项目中,常常需要使用定时器做一些轮询的操作,Node JS里面提供了两个全局函数setTimeoutsetInterval来实现,但是在使用中,定时任务往往是一些耗时操作,我们期望每一次轮询等操作做完了在重新开始定时器,因此需要对定时器进行暂停和恢复,所以对定时器进行了一个简单的封装,代码如下:

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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章