function func(){
const [time, setTime] = useState(10);
var timeRemaining = 10;
const myInterval = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining = timeRemaining - 1;
setTime(timeRemaining);
} else { clearInterval(myInterval) }
}, 1000);
return <div>{time}</div>
}
The code above works thanks to the variable timeRemaining
. However, it stops working if I remove that variable (in order to keep the code clean):
const myInterval = setInterval(() => {
if (time> 0) { setTime(time-1); }
else { clearInterval(myInterval); }
}, 1000);
By rewriting it in the above way, it stops updating time
.