-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
58 lines (48 loc) · 1.28 KB
/
index.ts
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
53
54
55
56
57
58
import { EventEmitter } from "events";
interface EventsMap {
tick: [];
start: [];
error: [Error];
}
(function (
timer: number,
callback: (error: Error | null, ticks?: number) => void
) {
const EMITTER = new EventEmitter<EventsMap>();
const MILLISECONDS_INTERVAL = 50;
let ticks = 0;
let elapsedTimeInMilliseconds = 0;
let intervalID: NodeJS.Timeout;
const TIMESTAMP_ERROR = new Error("Timestamp is divisile by 5");
function start() {
process.nextTick(() => tick());
intervalID = setInterval(itirate, MILLISECONDS_INTERVAL);
}
function itirate() {
if (elapsedTimeInMilliseconds >= timer) return stop();
elapsedTimeInMilliseconds += MILLISECONDS_INTERVAL;
Date.now() % 5 ? tick() : propagateError();
}
function tick() {
EMITTER.emit("tick");
ticks++;
}
function stop() {
clearInterval(intervalID);
return callback(null, ticks);
}
function propagateError() {
callback(TIMESTAMP_ERROR, ticks);
EMITTER.emit("error", TIMESTAMP_ERROR);
}
start();
return EMITTER;
})(1000, (error, result) => {
if (error) {
console.error(`Callback: ${error}`);
} else {
console.log(`Number of ticks: ${result}`);
}
})
.on("tick", () => console.log("Tick"))
.on("error", (error) => console.error(`Event: ${error}`));