Skip to content

Instantly share code, notes, and snippets.

@Zadigo
Created February 2, 2025 18:46
Show Gist options
  • Save Zadigo/922249b45e8fd80c3aaff49303b65bce to your computer and use it in GitHub Desktop.
Save Zadigo/922249b45e8fd80c3aaff49303b65bce to your computer and use it in GitHub Desktop.
export function useDebounce() {
function debounce<T extends (...args: any[]) => void>(func: T, wait: number, immediate: boolean = false) {
let timeout: ReturnType<typeof setTimeout> | null = null
// return function (this: any, ...callbackArgs: Parameters<T>) {
return function (...callbackArgs: Parameters<T>) {
// const context = this
function later() {
timeout = null
if (!immediate) {
// func.apply(context, callbackArgs)
func.apply(callbackArgs)
}
}
const callNow = immediate && !timeout
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(later, wait)
if (callNow) {
// func.apply(context, callbackArgs)
func.apply(callbackArgs)
}
}
}
return {
debounce
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment