|
| 1 | +/** |
| 2 | + * @fileoverview Throttle utility — limits how often a function can run. |
| 3 | + * Useful for scroll events, mouse moves, resize, etc. |
| 4 | + */ |
| 5 | + |
| 6 | +type ThrottledFunction<T extends (...args: any[]) => void> = (...args: Parameters<T>) => void; |
| 7 | + |
| 8 | +/** |
| 9 | + * Creates a throttled version of the given function. |
| 10 | + * @param fn - Function to throttle |
| 11 | + * @param interval - Minimum time (in ms) between calls |
| 12 | + * @returns A throttled function |
| 13 | + */ |
| 14 | +export function throttle<T extends (...args: any[]) => void>( |
| 15 | + fn: T, |
| 16 | + interval: number |
| 17 | +): ThrottledFunction<T> { |
| 18 | + if (typeof fn !== 'function') { |
| 19 | + throw new TypeError('[webdev-power-kit][throttle] First argument must be a function.'); |
| 20 | + } |
| 21 | + |
| 22 | + if (typeof interval !== 'number' || interval < 0) { |
| 23 | + throw new TypeError('[webdev-power-kit][throttle] Interval must be a non-negative number.'); |
| 24 | + } |
| 25 | + |
| 26 | + let lastCalled = 0; |
| 27 | + let timeoutId: ReturnType<typeof setTimeout> | null = null; |
| 28 | + |
| 29 | + return function throttledFn(...args: Parameters<T>) { |
| 30 | + const now = Date.now(); |
| 31 | + const timeSinceLastCall = now - lastCalled; |
| 32 | + |
| 33 | + if (timeSinceLastCall >= interval) { |
| 34 | + lastCalled = now; |
| 35 | + try { |
| 36 | + fn(...args); |
| 37 | + } catch (err) { |
| 38 | + console.error('[webdev-power-kit][throttle] Function threw an error:', err); |
| 39 | + } |
| 40 | + } else if (!timeoutId) { |
| 41 | + const timeRemaining = interval - timeSinceLastCall; |
| 42 | + timeoutId = setTimeout(() => { |
| 43 | + timeoutId = null; |
| 44 | + lastCalled = Date.now(); |
| 45 | + try { |
| 46 | + fn(...args); |
| 47 | + } catch (err) { |
| 48 | + console.error('[webdev-power-kit][throttle] Function threw an error:', err); |
| 49 | + } |
| 50 | + }, timeRemaining); |
| 51 | + } |
| 52 | + }; |
| 53 | +} |
0 commit comments