From c934eeaad879c166e991ab7a12fc134eb0c8dfa6 Mon Sep 17 00:00:00 2001 From: Damjan Savic Date: Sun, 25 Jan 2026 06:23:46 +0100 Subject: [PATCH] auto-claude: subtask-1-1 - Create throttle utility function --- src/utils/throttle.ts | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 src/utils/throttle.ts 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); + } + }; +}