-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker.mjs
40 lines (33 loc) · 798 Bytes
/
ticker.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { EventEmitter } from 'events';
/**
*
* @param {number} number
* @param {(n:number)=>any} callback
*/
function ticker(number, callback) {
const emitter = new EventEmitter();
let tick_count = 0;
setTimeout(() => callback(tick_count), number);
const ticker50 = () => {
process.nextTick(() => {
const t = new Date();
if (t%5 === 0) {
emitter.emit('error', new Error('tick error'));
} else {
emitter.emit('tick', t);
tick_count++;
};
});
setTimeout(() => {
ticker50();
}, 50);
};
ticker50();
return emitter;
}
const runningTicker = ticker(1000, (tick_count) => {
console.log(tick_count);
});
runningTicker
.on('tick', (t) => console.log(t))
.on('error', (err) => console.error(err.message));