From 88e82350bfa036e0db071c989c4f41bdcae5fd7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pau=20Ferrer=20Oca=C3=B1a?= Date: Tue, 8 Feb 2022 16:12:29 +0100 Subject: [PATCH] MOBILE-3808 utils: Add throttle function --- src/core/services/utils/utils.ts | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/core/services/utils/utils.ts b/src/core/services/utils/utils.ts index b928c0e5e..3ddee12d1 100644 --- a/src/core/services/utils/utils.ts +++ b/src/core/services/utils/utils.ts @@ -1541,7 +1541,6 @@ export class CoreUtilsProvider { /** * Debounce a function so consecutive calls are ignored until a certain time has passed since the last call. * - * @param context The context to apply to the function. * @param fn Function to debounce. * @param delay Time that must pass until the function is called. * @return Debounced function. @@ -1558,6 +1557,31 @@ export class CoreUtilsProvider { return debounced; } + /** + * Throttle a function so consecutive calls are ignored until a certain time has passed since the last executed call. + * + * @param fn Function to throttle. + * @param duration Time that must pass until the function is called. + * @return Throttled function. + */ + throttle(fn: (...args: T) => unknown, duration: number): (...args: T) => void { + let shouldWait = false; + + const throttled = (...args: T): void => { + if (!shouldWait) { + fn.apply(null, args); + + shouldWait = true; + + setTimeout(() => { + shouldWait = false; + }, duration); + } + }; + + return throttled; + } + /** * Check whether the app can scan QR codes. *