Home > OS >  how can I clear the timeout in this case?
how can I clear the timeout in this case?

Time:05-19

how can I clear the timeout in this case ?

Code:

  const [flag, setFlag] = useState<boolean>(false);

  const timerFlag = useRef<null | ReturnType<typeof setTimeout>>(null);

  const handlePressCancel2 = () => {
     timerFlag.current = setTimeout(() => {
     setFlag(true)
    }, 150);
  }

CodePudding user response:

If you want to clear the timeout when you destroy the component you must use an useEffect for this:

 const [flag, setFlag] = useState<boolean>(false);

 const timerFlag = useRef<null | ReturnType<typeof setTimeout>>(null);

 const handlePressCancel2 = () => {
    timerFlag.current = setTimeout(() => {
      setFlag(true);
    }, 150);
  };

 useEffect(() => {
    return () => {
      if (timerFlag.current) {
        clearTimeout(timerFlag.current);
      }
    };
 }, []);

CodePudding user response:

Try to make a return to clear the timing return () => clearTimeout(handlePressCancel2)

  • Related