diff --git a/public/scripts/utils.js b/public/scripts/utils.js index eb2f6b1b1..7a55ec3a7 100644 --- a/public/scripts/utils.js +++ b/public/scripts/utils.js @@ -270,6 +270,13 @@ export function getStringHash(str, seed = 0) { return 4294967296 * (2097151 & h2) + (h1 >>> 0); } +/** + * Map of debounced functions to their timers. + * Weak map is used to avoid memory leaks. + * @type {WeakMap} + */ +const debounceMap = new WeakMap(); + /** * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. * @param {function} func The function to debounce. @@ -281,9 +288,21 @@ export function debounce(func, timeout = debounce_timeout.standard) { return (...args) => { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, args); }, timeout); + debounceMap.set(func, timer); }; } +/** + * Cancels a scheduled debounced function. Does nothing if the function is not debounced or not scheduled. + * @param {function} func The function to cancel. + */ +export function cancelDebounce(func) { + if (debounceMap.has(func)) { + clearTimeout(debounceMap.get(func)); + debounceMap.delete(func); + } +} + /** * Creates a throttled function that only invokes func at most once per every limit milliseconds. * @param {function} func The function to throttle.