Add debounce cancelling

This commit is contained in:
Cohee 2024-07-22 22:20:03 +03:00
parent 8777526f8a
commit 17dc3fa4b5
1 changed files with 19 additions and 0 deletions

View File

@ -270,6 +270,13 @@ export function getStringHash(str, seed = 0) {
return 4294967296 * (2097151 & h2) + (h1 >>> 0); return 4294967296 * (2097151 & h2) + (h1 >>> 0);
} }
/**
* Map of debounced functions to their timers.
* Weak map is used to avoid memory leaks.
* @type {WeakMap<function, any>}
*/
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. * 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. * @param {function} func The function to debounce.
@ -281,9 +288,21 @@ export function debounce(func, timeout = debounce_timeout.standard) {
return (...args) => { return (...args) => {
clearTimeout(timer); clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout); 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. * Creates a throttled function that only invokes func at most once per every limit milliseconds.
* @param {function} func The function to throttle. * @param {function} func The function to throttle.