Skip to content

Instantly share code, notes, and snippets.

@PhilipWee
Created August 13, 2022 02:45
Show Gist options
  • Save PhilipWee/55b5e520c4df9db593bde96ec4914cae to your computer and use it in GitHub Desktop.
Save PhilipWee/55b5e520c4df9db593bde96ec4914cae to your computer and use it in GitHub Desktop.
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