-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker.fix.mjs
45 lines (38 loc) · 860 Bytes
/
ticker.fix.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
41
42
43
44
45
import { EventEmitter } from 'events';
/**
* @param {number} number
* @param {(n:number)=>any} callback
*/
function ticker(
number,
callback
) {
const emitter = new EventEmitter();
let tick_count = 0;
let ticker50 = () => {
if (ticker50 !== null) {
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);
}
};
setTimeout(() => {
ticker50 = null;
callback(tick_count);
}, number);
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));