0

let [seconds,setSeconds] = useState(59) useEffect(()=>{ setInterval(()=>{ setSeconds(seconds-1) },1000) }) Passing {seconds} in html timer starts. But it works like 59-58 and then it is decreasing along with different numbers. I need solution for this.

I tried using loops and other methods but didn't work.

I was expecting 59-58-57-56 to 00

1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Dec 14, 2022 at 11:32

1 Answer 1

1

The issue is that every time seconds changes your components gets re-rendered creating multiple instances of setInterval.

You need to wrap your setInterval in a useEffect in order to be able to clear it properly.

React.useEffect(() => {
    const timer =
      seconds > 0 && setInterval(() => setSeconds(seconds - 1), 1000);
    return () => clearInterval(timer);
  }, [seconds]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.