Created
February 2, 2025 18:46
-
-
Save Zadigo/922249b45e8fd80c3aaff49303b65bce to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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