( fn: (...args: T) => void, wait: number = 100, )
| 35 | * @returns the function that will be throttled |
| 36 | */ |
| 37 | export const throttle = <T extends unknown[]>( |
| 38 | fn: (...args: T) => void, |
| 39 | wait: number = 100, |
| 40 | ) => { |
| 41 | let inThrottle: boolean, |
| 42 | lastFn: ReturnType<typeof setTimeout>, |
| 43 | lastTime: number; |
| 44 | return (...args: T) => { |
| 45 | if (!inThrottle) { |
| 46 | fn.apply(this, args); |
| 47 | lastTime = Date.now(); |
| 48 | inThrottle = true; |
| 49 | } else { |
| 50 | clearTimeout(lastFn); |
| 51 | lastFn = setTimeout( |
| 52 | () => { |
| 53 | if (Date.now() - lastTime >= wait) { |
| 54 | fn.apply(this, args); |
| 55 | lastTime = Date.now(); |
| 56 | } |
| 57 | }, |
| 58 | Math.max(wait - (Date.now() - lastTime), 0), |
| 59 | ); |
| 60 | } |
| 61 | }; |
| 62 | }; |
no test coverage detected