Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use setInterval in react?

I'm trying to make a simple setInterval function for a typing game but it keeps glitching out depending on my syntax or not updating at all as it is now.

How do I get this to update every second and call the functions in the if statement?

const [counter, setCounter] = useState(10);

useEffect(() => {
  let timer = setInterval(() => {
    setCounter(counter - 1);

    if (counter === 0) {
      setWordIndex(wordIndex + 1);
      setLives(lives - 1);
      life.play();
      setCounter(10);
    }
  }, 1000);
}, []);

*********Edit***************

This is what I have now that is working. The first answer fixed the async issue of the counter not decrementing but I had to move the if statement outside of the useEffect to correct what I believe was caused by this same problem.

 useEffect(() => {
    let timer = setInterval(() => {
      setCounter( counter => counter - 1);
    }, 1000);
  }, []);
  if (counter == 0) {
    setWordIndex(wordIndex + 1);
    setLives(lives - 1);
    life.play();
    setCounter(10);
  }
like image 982
dnolan Avatar asked Oct 19 '25 09:10

dnolan


1 Answers

Use callback function in setCounter function. As you are calling the state update in an async function. it's good practice to update the state based on the previous state.

const [counter, setCounter] = useState(10);
useEffect(() => {
    let timer = setInterval(() => {
        setCounter(counter => {
            const updatedCounter = counter - 1;
            if (updatedCounter === 0) {
                setWordIndex(wordIndex + 1);
                setLives(lives - 1);
                life.play();
                return 10;
            }
            return updatedCounter;
        }); // use callback function to set the state

    }, 1000);
    return () => clearInterval(timer); // cleanup the timer
}, []);
like image 166
Sohail Ashraf Avatar answered Oct 21 '25 23:10

Sohail Ashraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!