Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Last active December 12, 2019 22:37
Show Gist options
  • Save andycarrell/92a0f478518585c5cb18aa1244b6cb86 to your computer and use it in GitHub Desktop.
Save andycarrell/92a0f478518585c5cb18aa1244b6cb86 to your computer and use it in GitHub Desktop.
function useTimeout() {
const ids = React.useRef([]);
React.useEffect(() => () => ids.current.forEach(clearTimeout), []);
// setTimeout takes a callback and a delay, then returns the id associated with the timeout.
const _setTimeout = React.useCallback((callback, delay) => {
const id = setTimeout(callback, delay);
ids.current.push(id);
return id;
}, []);
return _setTimeout;
}
function useSetTimeoutCleanup() {
const ids = React.useRef([]);
React.useEffect(() => () => ids.current.forEach(clearTimeout), []);
const withCleanup = React.callback(id => {
ids.current.push(id);
return id;
}, []);
return withCleanup;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment