File tree Expand file tree Collapse file tree 1 file changed +12
-20
lines changed
Expand file tree Collapse file tree 1 file changed +12
-20
lines changed Original file line number Diff line number Diff line change 1- /** A throttle that fires the first call immediately and ensures the last call during the duration is also fired. */
1+ //From: https://kettanaito.com/blog/debounce-vs-throttle
2+
3+ /** A very simple throttle. Will execute the function at the end of each period and discard any other calls during that period. */
24export function throttle (
35 func : ( ...args : any [ ] ) => void ,
46 durationMs : number
57) : ( ...args : any [ ] ) => void {
6- let timeoutId : NodeJS . Timeout | null = null ;
7- let nextArgs : any [ ] | null = null ;
8-
9- const wrapped = ( ...args : any [ ] ) => {
10- if ( timeoutId ) {
11- nextArgs = args ;
12- return ;
13- }
8+ let isPrimedToFire = false ;
149
15- func ( ...args ) ;
10+ return ( ...args : any [ ] ) => {
11+ if ( ! isPrimedToFire ) {
12+ isPrimedToFire = true ;
1613
17- timeoutId = setTimeout ( ( ) => {
18- timeoutId = null ;
19- if ( nextArgs ) {
20- const argsToUse = nextArgs ;
21- nextArgs = null ;
22- wrapped ( ...argsToUse ) ;
23- }
24- } , durationMs ) ;
14+ setTimeout ( ( ) => {
15+ func ( ...args ) ;
16+ isPrimedToFire = false ;
17+ } , durationMs ) ;
18+ }
2519 } ;
26-
27- return wrapped ;
2820}
You can’t perform that action at this time.
0 commit comments