Skip to content

Commit ec093a1

Browse files
committed
Add examples
1 parent 1701976 commit ec093a1

2 files changed

Lines changed: 89 additions & 0 deletions

File tree

JavaScript/1-theory.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
'use strict';
2+
3+
class Timer {
4+
constructor(interval) {
5+
this.interval = interval;
6+
this.listeners = new Set();
7+
this.instance = setInterval(() => {
8+
for (const callback of this.listeners.values()) {
9+
callback();
10+
}
11+
}, interval);
12+
}
13+
14+
listen(callback) {
15+
this.listeners.add(callback);
16+
}
17+
}
18+
19+
class TimerFactory {
20+
static timers = new Map();
21+
static getTimer(interval) {
22+
const timer = TimerFactory.timers.get(interval);
23+
if (timer) return timer;
24+
const instance = new Timer(interval);
25+
TimerFactory.timers.set(interval, instance);
26+
return instance;
27+
}
28+
}
29+
30+
class Interval {
31+
constructor(msec, callback) {
32+
this.timer = TimerFactory.getTimer(msec);
33+
this.timer.listen(callback);
34+
}
35+
}
36+
37+
// Usage
38+
39+
class Client {
40+
constructor(msec, count) {
41+
this.timers = [];
42+
for (let i = 0; i < count; i++) {
43+
new Interval(msec, () => {});
44+
}
45+
}
46+
}
47+
48+
const client1 = new Client(1000, 1000000);
49+
const client2 = new Client(2000, 1000000);
50+
console.log({ client1, client2 });
51+
const memory = process.memoryUsage();
52+
console.log({ memory });

JavaScript/2-simple.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
class Interval {
4+
static timers = new Map();
5+
6+
constructor(msec, callback) {
7+
let timer = Interval.timers.get(msec);
8+
if (!timer) {
9+
this.listeners = new Set();
10+
this.instance = setInterval(() => {
11+
for (const callback of this.listeners.values()) {
12+
callback();
13+
}
14+
}, msec);
15+
Interval.timers.set(msec, this);
16+
timer = this;
17+
}
18+
timer.listeners.add(callback);
19+
}
20+
}
21+
22+
// Usage
23+
24+
class Client {
25+
constructor(msec, count) {
26+
this.timers = [];
27+
for (let i = 0; i < count; i++) {
28+
new Interval(msec, () => {}, msec);
29+
}
30+
}
31+
}
32+
33+
const client1 = new Client(1000, 1000000);
34+
const client2 = new Client(2000, 1000000);
35+
console.log({ client1, client2 });
36+
const memory = process.memoryUsage();
37+
console.log({ memory });

0 commit comments

Comments
 (0)