diff --git a/src/utils/throttle.ts b/src/utils/throttle.ts new file mode 100644 index 0000000..c28bf2e --- /dev/null +++ b/src/utils/throttle.ts @@ -0,0 +1,40 @@ +/** + * Throttles a function to execute at most once per specified delay period. + * The first call executes immediately, then subsequent calls are throttled. + * + * @param func - The function to throttle + * @param delay - Minimum time in milliseconds between function executions + * @returns Throttled version of the function + */ +export function throttle any>( + func: T, + delay: number +): (...args: Parameters) => void { + let lastCall = 0; + let timeout: NodeJS.Timeout | null = null; + + return function (...args: Parameters) { + const now = Date.now(); + const timeSinceLastCall = now - lastCall; + + const execute = () => { + lastCall = Date.now(); + func(...args); + }; + + if (timeSinceLastCall >= delay) { + // Enough time has passed, execute immediately + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + execute(); + } else if (!timeout) { + // Schedule execution after remaining delay + timeout = setTimeout(() => { + timeout = null; + execute(); + }, delay - timeSinceLastCall); + } + }; +}