'setInterval function is running faster

setTimeout function is running faster than the given execution interval on useEffect hook.

const [minutes, setMinutes] = useState(QUESTIONS.exam_duration);
  const [seconds, setSeconds] = useState("00");
  useEffect(() => {
    let myInterval = setInterval(() => countDown(), 1000);
    return () => {
      clearInterval(myInterval);
    };
  });
  const countDown = () => {
    if (seconds > 0) {
      setSeconds(seconds - 1);
      console.log(minutes, seconds);
    }
    if (seconds == 0) {
      if (minutes == 0) {
        clearInterval(myInterval);
      } else {
        setMinutes(minutes - 1);
        setSeconds(59);
      }
    }
  };


Solution 1:[1]

Maybe you should just execute the useEffect only one time at load...

  useEffect(() => {
    let myInterval = setInterval(() => countDown(), 1000);
    return () => {
      clearInterval(myInterval);
    };
  }, []);  // <-- Add the empty array here...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BENARD Patrick