Skip to content

Instantly share code, notes, and snippets.

@sbin0819
Created April 21, 2023 07:42
Show Gist options
  • Save sbin0819/3670dba7f8f207c7a4b0deb01c5f2ff5 to your computer and use it in GitHub Desktop.
Save sbin0819/3670dba7f8f207c7a4b0deb01c5f2ff5 to your computer and use it in GitHub Desktop.
const useInterval = (callback: Function, delay?: number | null) => {
  const savedCallback = useRef<Function>(() => {});

  useEffect(() => {
    savedCallback.current = callback;
  });

  useEffect(() => {
    if (delay !== null) {
      const interval = setInterval(() => savedCallback.current(), delay || 0);
      return () => clearInterval(interval);
    }

    return undefined;
  }, [delay]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment