javascriptreactjsstatesettimeoutcleartimeout

can not stop interval


I have a state that updates the time every second with setTimeout, but I can not clear it with ClearTimeout. When I print timerClear value, it shows me different values.

var timerClear ;

const [MyTime, setMyTime] = useState('');

useEffect(() => {
  timerClear = setInterval(() => {
     setMyTime(
       realeTime.toLocaleTimeString([], {
       timeZone: "Asia/Tehran",
       hour: '2-digit',
       minute: '2-digit',
       second: '2-digit',
       hour12: false,
       }),
     );

     checkTime();

  }, 1000);
}, [MyTime]);

In the check function, if the time reaches the desired value, I clear all the timers

if (filterGetTime > filterEndTime) {
   if (data.examParents[0].examParent_method == "0") { 
      console.log('timerClear',timerClear);
                    
      alert('زمان امتحان تمام شده است!!!');
      if(sendReqDelay){
         clearTimeout(sendReqDelay);
      }
      clearTimeout(setTimeToPageTimeOut);
      clearTimeout(TimerIntervalSolveQuestions);
      clearInterval(timerClear);
   } 
             
}

After each confirmation of the button in Alert

alert('زمان امتحان تمام شده است!!!');
console.log('timerClear',timerClear);

Prints another number.


Solution

  • Because of the dependency array [MyTime] every time MyTime changes, you're creating a new interval and the reference to old interval is lost. With such setup you're better off using a setTimeout.

    Also since you have a normal variable, it is redeclared on every re-render.
    If you're going to use setInterval you should be using a useRef to keep reference to it and remove MyTime from dependency array.


    Something along the lines of:

    const timerClear = useRef() ;
    const [myTime, setMyTime] = useState('');
    
    useEffect(() => {
      timerClear.current = setInterval(() => {
         setMyTime(
            // ...
         );
      }, 1000);
      return () => clearInterval(timeClear.current);
    }, []);