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) {
271}271}
272272
273/**273/**
274 * Map of debounced functions to their timers.
275 * Weak map is used to avoid memory leaks.
276 * @type {WeakMap<function, any>}
277 */
278const debounceMap = new WeakMap();
279
280/**
274 * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.281 * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked.
275 * @param {function} func The function to debounce.282 * @param {function} func The function to debounce.
276 * @param {debounce_timeout|number} [timeout=debounce_timeout.default] The timeout based on the common enum values, or in milliseconds.283 * @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) {
281 return (...args) => {288 return (...args) => {
282 clearTimeout(timer);289 clearTimeout(timer);
283 timer = setTimeout(() => { func.apply(this, args); }, timeout);290 timer = setTimeout(() => { func.apply(this, args); }, timeout);
291 debounceMap.set(func, timer);
284 };292 };
285}293}
286294
287/**295/**
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 */
299export function cancelDebounce(func) {
300 if (debounceMap.has(func)) {
301 clearTimeout(debounceMap.get(func));
302 debounceMap.delete(func);
303 }
304}
305
306/**
288 * Creates a throttled function that only invokes func at most once per every limit milliseconds.307 * Creates a throttled function that only invokes func at most once per every limit milliseconds.
289 * @param {function} func The function to throttle.308 * @param {function} func The function to throttle.
290 * @param {number} [limit=300] The limit in milliseconds.309 * @param {number} [limit=300] The limit in milliseconds.