Last active
September 3, 2023 23:35
-
-
Save KonnorRogers/7b4f6d223a6e89ee54ef91f59547fdd7 to your computer and use it in GitHub Desktop.
debouncing in a class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Base { | |
constructor () { | |
super() | |
/** | |
* @type {null | Map<object | string | number | symbol, ReturnType<typeof setTimeout>>} | |
*/ | |
this.__debounceMap__ = null | |
} | |
/** | |
* @param {(...args: any[]) => any} callback | |
* @param {{ key: any, wait?: number }} options | |
* @return {ReturnType<typeof setTimeout>} | |
*/ | |
debounce (callback, options) { | |
if (this.__debounceMap__ == null) { | |
this.__debounceMap__ = new Map() | |
} | |
if (options.wait == null) options.wait = 0 | |
let timeout = this.__debounceMap__.get(options.key) | |
if (timeout) { | |
clearTimeout(timeout) | |
} | |
timeout = setTimeout(() => { | |
callback() | |
}, options.wait) | |
this.__debounceMap__.set(options.key, timeout) | |
return timeout | |
} | |
} | |
// Usage | |
class MyClass extends Base { | |
doExpensiveThing () { | |
this.debounce(() => { | |
this.calculateAllTheThing() | |
}, { wait: 300, key: this.doExpensiveThing }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment