Add debounce cancelling

17dc3fa4b50746874cc870dd68cdd8c92cb58515

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +19 -0Ignore whitespace
public/scripts/utils.js+19 -0
@@ -271,6 +271,13 @@ export function getStringHash(str, seed = 0) {
271271}
272272
273273/**
274+ * Map of debounced functions to their timers.
275+ * Weak map is used to avoid memory leaks.
276+ * @type {WeakMap<function, any>}
277+ */
278+const debounceMap = new WeakMap();
279+
280+/**
274281 * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
275282 * @param {function} func The function to debounce.
276283 * @param {debounce_timeout|number} [timeout=debounce_timeout.default] The timeout based on the common enum values, or in milliseconds.
@@ -281,10 +288,22 @@ export function debounce(func, timeout = debounce_timeout.standard) {
281288 return (...args) => {
282289 clearTimeout(timer);
283290 timer = setTimeout(() => { func.apply(this, args); }, timeout);
291+ debounceMap.set(func, timer);
284292 };
285293}
286294
287295/**
296+ * Cancels a scheduled debounced function. Does nothing if the function is not debounced or not scheduled.
297+ * @param {function} func The function to cancel.
298+ */
299+export function cancelDebounce(func) {
300+ if (debounceMap.has(func)) {
301+ clearTimeout(debounceMap.get(func));
302+ debounceMap.delete(func);
303+ }
304+}
305+
306+/**
288307 * Creates a throttled function that only invokes func at most once per every limit milliseconds.
289308 * @param {function} func The function to throttle.
290309 * @param {number} [limit=300] The limit in milliseconds.