How to build a timer with event trigger in node?

We all know that the asynchronism of node makes it inconvenient to do any timing function.

for example, after starting timer A, funtion B is executed one second later. But as long as event C occurs halfway, functionD, is triggered immediately and A retiming. How can a function like this be implemented?

May.22,2021

all know that node's asynchronism makes it inconvenient to do any timing function

I really don't know, except that the timing is not accurate (there are other tasks performing timer ). node there are many modules such as node-schedule that can handle scheduled tasks.

for example, after timer An is started, funtion B is executed one second later. But as long as event C occurs halfway, functionD, is triggered immediately and A retiming. How can a function like this be implemented?

of course, if that's all you need, it's easy to deal with. Take a chestnut.

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) { //10reset
    if (i < 10) {
        iPP;
        setTimeout((j) => {
            mte.emit('reset');
            test(j);
        }, 500, i)
    }
}
test()
Menu