| 784 | * @returns Throttled function |
| 785 | */ |
| 786 | export function throttle<T extends (...args: unknown[]) => unknown>( |
| 787 | fn: T, |
| 788 | limit: number |
| 789 | ): (...args: Parameters<T>) => void { |
| 790 | let lastCall = 0; |
| 791 | let timeoutId: ReturnType<typeof setTimeout> | null = null; |
| 792 | |
| 793 | return (...args: Parameters<T>) => { |
| 794 | const now = Date.now(); |
| 795 | const remaining = limit - (now - lastCall); |
| 796 | |
| 797 | if (remaining <= 0) { |
| 798 | if (timeoutId) { |
| 799 | clearTimeout(timeoutId); |
| 800 | timeoutId = null; |
| 801 | } |
| 802 | lastCall = now; |
| 803 | fn(...args); |
| 804 | } else if (!timeoutId) { |
| 805 | timeoutId = setTimeout(() => { |
| 806 | lastCall = Date.now(); |
| 807 | timeoutId = null; |
| 808 | fn(...args); |
| 809 | }, remaining); |
| 810 | } |
| 811 | }; |
| 812 | } |
| 813 | |
| 814 | /** |
| 815 | * Estimate memory usage of an object (rough approximation) |