鍍金池/ 問(wèn)答/HTML/ 在node里如何構(gòu)建一個(gè)帶事件觸發(fā)的計(jì)時(shí)器?

在node里如何構(gòu)建一個(gè)帶事件觸發(fā)的計(jì)時(shí)器?

都知道node的異步讓它搞什么定時(shí)功能都不方便,

比如啟動(dòng)定時(shí)器A后,一秒鐘后執(zhí)行funtion B。但只要中途出現(xiàn)了事件C,那么即時(shí)觸發(fā)functionD,然后A重新記時(shí)。像這種功能該如何實(shí)現(xiàn)?

回答
編輯回答
心上人
都知道node的異步讓它搞什么定時(shí)功能都不方便

這個(gè)還真不知道,除了時(shí)間不太準(zhǔn)(有別的任務(wù)在執(zhí)行沒(méi)空檢測(cè)timer)。node有很多模塊如 node-schedule可以處理定時(shí)任務(wù)。

比如啟動(dòng)定時(shí)器A后,一秒鐘后執(zhí)行funtion B。但只要中途出現(xiàn)了事件C,那么即時(shí)觸發(fā)functionD,然后A重新記時(shí)。像這種功能該如何實(shí)現(xiàn)?

當(dāng)然如果你的需求只是這樣其實(shí)處理起來(lái)也很簡(jiǎn)單,舉個(gè)栗子。

const EventEmitter = require('events');

class MyTimerEmitter extends EventEmitter {

    constructor() {
        super();
        this._timerA = null;
    }

    run() {
        this._timerA = setTimeout(() => { console.log('finish') }, 1000)
    }

    reset() {
        clearTimeout(this._timerA);
        this.run();
    }
}

const mte = new MyTimerEmitter();
mte.on('reset', function() {
    console.log('reset!');
    this.reset();
});

mte.run();


function test(i = 0) { //測(cè)試途中觸發(fā)了10次reset事件
    if (i < 10) {
        i++;
        setTimeout((j) => {
            mte.emit('reset');
            test(j);
        }, 500, i)
    }
}
test()
2018年8月4日 20:46