Skip to content

Instantly share code, notes, and snippets.

@Andrewnt219
Created July 27, 2021 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andrewnt219/e83f948247719bc84f5f2fd35110bafb to your computer and use it in GitHub Desktop.
Save Andrewnt219/e83f948247719bc84f5f2fd35110bafb to your computer and use it in GitHub Desktop.
function useInterval(callback, delay) {
const intervalRef = React.useRef(null);
const savedCallback = React.useRef(callback);
React.useEffect(() => {
savedCallback.current = callback;
});
React.useEffect(() => {
const tick = () => savedCallback.current();
if (typeof delay === 'number') {
intervalRef.current = window.setInterval(tick, delay);
return () => window.clearInterval(intervalRef.current);
}
}, [delay]);
return intervalRef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment