-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path3.3-ticker-mod.js
45 lines (35 loc) · 1 KB
/
3.3-ticker-mod.js
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';
// 1 main ticker function
function ticker(timer, callback) {
const eventEmitter = new EventEmitter();
let tick = 0;
const TICK_INTERVAL = 50;
const tickStart = new Date();
const emitTick = () => {
emitter.emit('tick', tick);
tick++;
}
// +++ 3.3 added line
process.nextTick(emitTick);
setTimeout(function recursiveTimeout() {
// if timer has passed, terminate and return result
if (new Date() - tickStart >= timer) {
return callback(null, tick);
}
emitTick();
// call recursively for next emit
setTimeout(recursiveTimeout, TICK_INTERVAL);
}, TICK_INTERVAL);
return eventEmitter;
}
// 2 initialize ticker event emitter
const emitter = ticker(1200, (err, tick) => {
if (err) {
return console.log('Callback error', err);
}
console.log(`Totally ticked ${tick} times`);
});
// 3 add listeners
emitter
.on('error', err => console.log('Emitted error', err))
.on('tick', (result) => console.log('Tick #', result));