Resetting interval depending on boolean state

Viewed 32

is there any way to reset this timer if modal boolean is false?

I want it to work only if modal appears, and reset immediately after modal is closed.

useEffect(() => {
    if (modal) {
      const timer = setInterval(() => {
        if (countRef.current >= 10) {
          clearInterval(timer);
        } else {
          setCount((count) => count + 1);
        }
      }, 1000);
    }
    if (!modal) {
     clear interval here and reset counter, is this possible?
    }

  }, [modal]);
1 Answers

You have to store the destroy function from the interval too.

// tsx

interface AppProps {
  modal: boolean;
}

const App = ({ modal }: AppProps) => {
  const intervalRef = useRef<ReturnType<typeof setInterval>>(null);
  const countRef = useRef(0);
  const setCount = (handler: (param: number) => number) =>
    (countRef.current = handler(countRef.current));

  useEffect(() => {
    if (modal) {
      intervalRef.current = setInterval(() => {
        if (countRef.current >= 10) {
          clearInterval(intervalRef.current);
        } else {
          setCount((count) => count + 1);
        }
      }, 1000);
    }
    if (!modal && intervalRef.current) {
      clearInterval(intervalRef.current);
      setCount((count) => count + 1);
    }

    return () => {
      clearInterval(intervalRef.current);
    }

  }, [modal]);

  return <div>hello</div>;
};
// jsx

const App = ({ modal }) => {
  const intervalRef = useRef(null);
  const countRef = useRef(0);
  const setCount = (handler) =>
    (countRef.current = handler(countRef.current));

  useEffect(() => {
    if (modal) {
      intervalRef.current = setInterval(() => {
        if (countRef.current >= 10) {
          clearInterval(intervalRef.current);
        } else {
          setCount((count) => count + 1);
        }
      }, 1000);
    }
    if (!modal && intervalRef.current) {
      clearInterval(intervalRef.current);
      setCount((count) => count + 1);
    }

    return () => {
      clearInterval(intervalRef.current);
    }

  }, [modal]);

  return <div>hello</div>;
};
Related