File tree Expand file tree Collapse file tree 1 file changed +20
-12
lines changed
Expand file tree Collapse file tree 1 file changed +20
-12
lines changed Original file line number Diff line number Diff line change 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. */
1+ /** A throttle that fires the first call immediately and ensures the last call during the duration is also fired. */
42export function throttle (
53 func : ( ...args : any [ ] ) => void ,
64 durationMs : number
75) : ( ...args : any [ ] ) => void {
8- let isPrimedToFire = false ;
9-
10- return ( ...args : any [ ] ) => {
11- if ( ! isPrimedToFire ) {
12- isPrimedToFire = true ;
6+ let timeoutId : NodeJS . Timeout | null = null ;
7+ let nextArgs : any [ ] | null = null ;
138
14- setTimeout ( ( ) => {
15- func ( ... args ) ;
16- isPrimedToFire = false ;
17- } , durationMs ) ;
9+ const wrapped = ( ... args : any [ ] ) => {
10+ if ( timeoutId ) {
11+ nextArgs = args ;
12+ return ;
1813 }
14+
15+ func ( ...args ) ;
16+
17+ timeoutId = setTimeout ( ( ) => {
18+ timeoutId = null ;
19+ if ( nextArgs ) {
20+ const argsToUse = nextArgs ;
21+ nextArgs = null ;
22+ wrapped ( ...argsToUse ) ;
23+ }
24+ } , durationMs ) ;
1925 } ;
26+
27+ return wrapped ;
2028}
You can’t perform that action at this time.
0 commit comments