Add debounce cancelling
| @@ -271,6 +271,13 @@ export function getStringHash(str, seed = 0) { | |||
| 271 | } | 271 | } |
| 272 | 272 | ||
| 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 | */ | ||
| 278 | const 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 | } |
| 286 | 294 | ||
| 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 | */ | ||
| 299 | export 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. |