Created
August 13, 2022 02:45
-
-
Save PhilipWee/55b5e520c4df9db593bde96ec4914cae to your computer and use it in GitHub Desktop.
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
import { useState } from "react"; | |
type SomeFunction = (...args: any[]) => void; | |
function useDebounce<Func extends SomeFunction>(func: Func, delay) { | |
const [timer, setTimer] = useState(); //Create timer state | |
const debouncedFunction = ((...args) => { | |
const newTimer = setTimeout(() => { | |
func(...args); | |
}, delay); | |
clearTimeout(timer); //Cancel previous timers | |
setTimer(newTimer); //Save latest timer | |
}) as Func; | |
return debouncedFunction; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment