File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 } ) ;
Original file line number Diff line number Diff line change 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 } ) ;
You can’t perform that action at this time.
0 commit comments