(callback: T)
| 1 | export function throttle<T extends(...args: any[]) => any>(callback: T): T & {cancel: () => void} { |
| 2 | let pending = false; |
| 3 | let frameId: number | null = null; |
| 4 | let lastArgs: any[]; |
| 5 | |
| 6 | const throttled: T = ((...args: any[]) => { |
| 7 | lastArgs = args; |
| 8 | if (frameId) { |
| 9 | pending = true; |
| 10 | } else { |
| 11 | callback(...lastArgs); |
| 12 | frameId = requestAnimationFrame(() => { |
| 13 | frameId = null; |
| 14 | if (pending) { |
| 15 | callback(...lastArgs); |
| 16 | pending = false; |
| 17 | } |
| 18 | }); |
| 19 | } |
| 20 | }) as any; |
| 21 | |
| 22 | const cancel = () => { |
| 23 | // TODO: resolve cast once types are updated |
| 24 | cancelAnimationFrame(frameId!); |
| 25 | pending = false; |
| 26 | frameId = null; |
| 27 | }; |
| 28 | |
| 29 | return Object.assign(throttled, {cancel}); |
| 30 | } |
| 31 | |
| 32 | type Task = () => void; |
| 33 |
no outgoing calls
no test coverage detected