From 2e6fc0e858d8352c425774236e8f87dbed460b04 Mon Sep 17 00:00:00 2001 From: Ilia Mashkov Date: Thu, 12 Feb 2026 10:29:52 +0300 Subject: [PATCH] feat(throttle): add tohrottling util --- src/shared/lib/utils/throttle/throttle.ts | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/shared/lib/utils/throttle/throttle.ts diff --git a/src/shared/lib/utils/throttle/throttle.ts b/src/shared/lib/utils/throttle/throttle.ts new file mode 100644 index 0000000..4bb0c90 --- /dev/null +++ b/src/shared/lib/utils/throttle/throttle.ts @@ -0,0 +1,32 @@ +/** + * Throttle function execution to a maximum frequency. + * + * @param fn Function to throttle. + * @param wait Maximum time between function calls. + * @returns Throttled function. + */ +export function throttle any>( + fn: T, + wait: number, +): (...args: Parameters) => void { + let lastCall = 0; + let timeoutId: ReturnType | null = null; + + return (...args: Parameters) => { + const now = Date.now(); + const timeSinceLastCall = now - lastCall; + + if (timeSinceLastCall >= wait) { + lastCall = now; + fn(...args); + } else { + // Schedule for end of wait period + if (timeoutId) clearTimeout(timeoutId); + timeoutId = setTimeout(() => { + lastCall = Date.now(); + fn(...args); + timeoutId = null; + }, wait - timeSinceLastCall); + } + }; +}