Harsh Mehta
Harsh Mehta

Reputation: 1

Facing problems in creating a Timer in React Js

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

Upvotes: 0

Views: 45

Answers (1)

leo
leo

Reputation: 111

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]);

Upvotes: 1

Related Questions