Skip to content

Instantly share code, notes, and snippets.

@KonnorRogers
Last active September 3, 2023 23:35
Show Gist options
  • Save KonnorRogers/7b4f6d223a6e89ee54ef91f59547fdd7 to your computer and use it in GitHub Desktop.
Save KonnorRogers/7b4f6d223a6e89ee54ef91f59547fdd7 to your computer and use it in GitHub Desktop.
debouncing in a class
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