| 808 | * @returns Throttled function |
| 809 | */ |
| 810 | export function throttle<T extends (...args: unknown[]) => unknown>( |
| 811 | fn: T, |
| 812 | limit: number |
| 813 | ): (...args: Parameters<T>) => void { |
| 814 | let lastCall = 0; |
| 815 | let timeoutId: ReturnType<typeof setTimeout> | null = null; |
| 816 | |
| 817 | return (...args: Parameters<T>) => { |
| 818 | const now = Date.now(); |
| 819 | const remaining = limit - (now - lastCall); |
| 820 | |
| 821 | if (remaining <= 0) { |
| 822 | if (timeoutId) { |
| 823 | clearTimeout(timeoutId); |
| 824 | timeoutId = null; |
| 825 | } |
| 826 | lastCall = now; |
| 827 | fn(...args); |
| 828 | } else if (!timeoutId) { |
| 829 | timeoutId = setTimeout(() => { |
| 830 | lastCall = Date.now(); |
| 831 | timeoutId = null; |
| 832 | fn(...args); |
| 833 | }, remaining); |
| 834 | } |
| 835 | }; |
| 836 | } |
| 837 | |
| 838 | /** |
| 839 | * Estimate memory usage of an object (rough approximation) |