-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.js
More file actions
69 lines (59 loc) · 1.45 KB
/
1-theory.js
File metadata and controls
69 lines (59 loc) · 1.45 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
'use strict';
class Timer {
constructor(interval, removeTimer) {
this.interval = interval;
this.listeners = new Set();
this.removeTimer = removeTimer;
this.instance = setInterval(() => {
for (const callback of this.listeners.values()) {
callback();
}
}, interval);
}
listen(callback) {
this.listeners.add(callback);
}
remove(callback) {
this.listeners.delete(callback);
if (this.listeners.size === 0) {
clearInterval(this.instance);
this.removeTimer();
}
}
}
class TimerFactory {
static timers = new Map();
static getTimer(interval) {
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 {
constructor(interval, callback) {
this.callback = callback;
this.timer = TimerFactory.getTimer(interval);
this.timer.listen(callback);
}
stop() {
this.timer.remove(this.callback);
}
}
// Usage
class Client {
constructor(interval, count) {
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 });