-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.ts
More file actions
75 lines (64 loc) · 1.66 KB
/
1-theory.ts
File metadata and controls
75 lines (64 loc) · 1.66 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class Timer {
interval: number;
listeners: Set<Function>;
removeTimer: Function;
instance: number;
constructor(interval: number, removeTimer: Function) {
this.interval = interval;
this.listeners = new Set();
this.removeTimer = removeTimer;
this.instance = setInterval(() => {
for (const callback of this.listeners.values()) {
callback();
}
}, interval);
}
listen(callback: Function) {
this.listeners.add(callback);
}
remove(callback: Function) {
this.listeners.delete(callback);
if (this.listeners.size === 0) {
clearInterval(this.instance);
this.removeTimer();
}
}
}
class TimerFactory {
static timers: Map<number, Timer> = new Map();
static getTimer(interval: number) {
const removeTimer = () => {
TimerFactory.timers.delete(interval);
};
const timer = TimerFactory.timers.get(interval);
if (timer) return timer;
const instance = new Timer(interval, removeTimer);
TimerFactory.timers.set(interval, instance);
return instance;
}
}
class Interval {
callback: Function
timer: Timer;
constructor(interval: number, callback: Function) {
this.callback = callback;
this.timer = TimerFactory.getTimer(interval);
this.timer.listen(callback);
}
stop() {
this.timer.remove(this.callback);
}
}
// Usage
class Client {
constructor(interval: number, count: number) {
for (let i = 0; i < count; i++) {
new Interval(interval, () => {});
}
}
}
const client1 = new Client(1000, 1000000);
const client2 = new Client(2000, 1000000);
console.log({ client1, client2 });
const memory = process.memoryUsage();
console.log({ memory });