Home > front end >  Index not resetting in setInterval()
Index not resetting in setInterval()

Time:01-18

I am trying to increment an index after every seconds using setInterval() and reset the index back to initial state after a particular condition, but the index is not resetting. I logged the index to the console to see the increment in action but after the condition is reached the index continue increasing instead of resetting back to the initial state. I expect the index to go back to zero and start incrementing again after index is above 10 as stated in the conditionals

The code is shown below;


export default function Gallery() {
  const [i, setI] = useState(0);

  function handleClick() {
    setInterval(() => {
      if (i < 10) {
        setI(prev => prev   1);
      } else {
        setI(0);
      }
    }, 1000)
  }

  console.log(i)

  return (
    <>
    </>
  );
}```

CodePudding user response:

In your first SetI, you use lambda expression. Maybe, you should try to use a lambda expression to the second call. Something like this:

    function handleClick() {
    setInterval(() => {
      if (i < 10) {
        setI(prev => prev   1);
      } else {
        setI(prev => 0);
      }
    }, 1000)
  }

But the answer above should work too.

CodePudding user response:

The i is not updating anymore in your if statement so it will always be the initial 0 value. Instead you can place the if statement in your setI so you'll have access to the up-to-date value.

function handleClick() {
  setInterval(() => {
    setI((prev) => {
      if (prev < 10) {
        return prev   1;
      } else {
        return 0;
      }
    });
  }, 1000);
}
  • Related