Skip to content

Instantly share code, notes, and snippets.

@weslleyaraujo
Created April 28, 2021 21:49
Show Gist options
  • Save weslleyaraujo/ef9adcd47b9633f4b5508c8078beb8d2 to your computer and use it in GitHub Desktop.
Save weslleyaraujo/ef9adcd47b9633f4b5508c8078beb8d2 to your computer and use it in GitHub Desktop.
function useTimeout(callback: () => void, delay = 1000 * 5) {
const callbackRef = useRef<typeof callback | null>(null);
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
useEffect(() => {
function execute() {
callbackRef.current?.();
}
if (delay) {
const id = setTimeout(execute, delay);
return () => clearTimeout(id);
}
}, [callback, delay]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment