Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created May 8, 2020 21:40
Show Gist options
  • Save andycarrell/d54742f2d089c4e942014af558b47def to your computer and use it in GitHub Desktop.
Save andycarrell/d54742f2d089c4e942014af558b47def to your computer and use it in GitHub Desktop.
export default function useTimeout() {
const ids = useRef([]);
React.useEffect(() => {
const cleanupTimeouts = () => {
ids.current.forEach(clearTimeout);
};
return cleanupTimeouts;
}, []);
// setTimeout takes a callback and a delay, then returns the id associated with the timeout.
return useCallback((callback, delay) => {
const id = setTimeout(callback, delay);
ids.current.push(id);
return id;
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment