Skip to content

Instantly share code, notes, and snippets.

@markmur
Last active August 19, 2022 13:13
Show Gist options
  • Save markmur/32a2ac075faf5d1f843729994284f0dd to your computer and use it in GitHub Desktop.
Save markmur/32a2ac075faf5d1f843729994284f0dd to your computer and use it in GitHub Desktop.
Debounce
function debounce<T>(fn: (...args: any[]) => Promise<T>, ms: number = 300) {
let timer: number | undefined
return (...args: any[]): Promise<T> => {
clearTimeout(timer)
return new Promise((resolve, reject) => {
timer = window.setTimeout(
() =>
fn(...args)
.then(resolve)
.catch(reject),
ms,
)
})
}
}
function debounce(fn, ms) {
let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => {
fn(...args)
}, ms)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment