Shaux
Shaux

Reputation: 33

React Native countdown setInterval not working

I am trying to create a countdown timer using useEffect hook and setInterval function, but it is not ever executing the code when the timer reaches 0. Also, when I console.log the value of the countdown variable it doesn't decrement.


  // set up counter for (un)flipped phone countdown
  // countdown of 20 seconds
  const [countdown, setCountdown] = useState(20);
  let intervalID: any;

  // on initialize
  useEffect(() => {
    // every second reduce countdown by 1
    intervalID = setInterval(() => {
      setCountdown(countdown - 1);
    }, 1000);

    return () => clearInterval(intervalID);
  }, []);

  // check if countdown has reached 0
  useEffect(() => {
    if (countdown == 0) {
      timerReset();
      alert("TIMER RESET");
      clearInterval(intervalID);
    }
  }, []);

Upvotes: 0

Views: 792

Answers (2)

J.dev
J.dev

Reputation: 1045

You can try this :

const [countdown, setCountdown] = useState(20);

useEffect(() => {
  let intervalID = setInterval(() => {
    setCountdown(prev => {
      if (prev === 0) clearInterval(intervalID);   // handle the condition here
      return prev - 1;
    });
  }, 1000);
  return () => clearInterval(intervalID);
}, []);

Upvotes: 1

windowsill
windowsill

Reputation: 3649

The code in the body of your component functions runs in every render. Which means you are setting interval id to undefined on every render. Use useRef to store the value instead.

And your second effect shouldn't be a mount effect, it needs to have count down as a dependency. Make sure to read all the docs on useEffect.

Upvotes: 0

Related Questions