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 Interval {
4+ static timers = new Map ( ) ;
5+
6+ constructor ( msec , callback ) {
7+ this . callback = callback ;
8+ const timer = Interval . timers . get ( msec ) ;
9+ if ( timer ) {
10+ Object . setPrototypeOf ( this , timer ) ;
11+ } else {
12+ this . listeners = new Set ( ) ;
13+ this . instance = setInterval ( ( ) => {
14+ for ( const callback of this . listeners . values ( ) ) {
15+ callback ( ) ;
16+ }
17+ } , msec ) ;
18+ Interval . timers . set ( msec , this ) ;
19+ }
20+ this . listeners . add ( this . callback ) ;
21+ }
22+
23+ remove ( ) {
24+ this . listeners . delete ( this . callback ) ;
25+ if ( this . listeners . length === 0 ) {
26+ clearInterval ( this . instance ) ;
27+ Interval . timers . delete ( this ) ;
28+ }
29+ }
30+ }
31+
32+ // Usage
33+
34+ const COUNT = 1000000 ;
35+ for ( let i = 0 ; i < COUNT ; i ++ ) {
36+ new Interval ( 1000 , ( ) => { } ) ;
37+ new Interval ( 2000 , ( ) => { } ) ;
38+ }
39+ const memory = process . memoryUsage ( ) ;
40+ console . log ( { memory } ) ;
You can’t perform that action at this time.
0 commit comments