-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
52 lines (42 loc) · 1.12 KB
/
index.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
46
47
48
49
50
51
52
import { EventEmitter } from "events";
/**
* @description A function that emits a tick event every 50ms and stops after the given timer of ticks is reached.
* @param {Number} timer
* @param {CallableFunction} cb
* @returns {EventEmitter}
*/
const ticker = (timer, cb) => {
const INTERVAL = 50;
const tick = new EventEmitter();
let ticks = 0;
const startTime = Date.now();
const emitTick = () => {
ticks += 1;
tick.emit("tick", Date.now() - startTime);
};
const tickTock = () => {
if (Date.now() - startTime >= timer) {
return cb(null, ticks);
}
setTimeout(() => {
emitTick();
return tickTock();
}, INTERVAL);
};
tickTock();
return tick;
};
//* Example usage: node index.js 500 (to fire 500 tick events) */
(() => {
const input = parseInt(process.argv[2]);
if (isNaN(input)) {
console.log("Please provide a number as an argument");
return;
}
const tick = ticker(input, (_, data) => {
console.log(`Exactly ${data} tick events fired`);
});
tick
.on("tick", (time) => console.log(`Tick after ${time}ms`))
.on("error", console.error);
})();