Reputation: 1
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
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