File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ 'use strict' ;
2+
3+ // Function throttling, executed once per interval
4+
5+ const throttle = ( timeout , fn , ...args ) => {
6+ let timer ;
7+ let wait = false ;
8+ let wrapped = null ;
9+
10+ const throttled = ( ...par ) => {
11+ timer = undefined ;
12+ if ( wait ) wrapped ( ...par ) ;
13+ } ;
14+
15+ wrapped = ( ...par ) => {
16+ if ( ! timer ) {
17+ timer = setTimeout ( throttled , timeout , ...par ) ;
18+ wait = false ;
19+ return fn ( ...args . concat ( par ) ) ;
20+ } else {
21+ wait = true ;
22+ }
23+ } ;
24+
25+ return wrapped ;
26+ } ;
27+
28+ // Usage
29+
30+ const fn = ( ...args ) => {
31+ console . log ( 'Function called, args: ' + args ) ;
32+ } ;
33+
34+ const ft = throttle ( 200 , fn , 'value1' ) ;
35+
36+ const timer = setInterval ( ( ) => {
37+ fn ( 'value2' ) ;
38+ ft ( 'value3' ) ;
39+ } , 50 ) ;
40+
41+ setTimeout ( ( ) => {
42+ clearInterval ( timer ) ;
43+ } , 2000 ) ;
You can’t perform that action at this time.
0 commit comments