I implemented a timer which works fine but the only problem is that it doesn't clearInterval when the timer ends .
My code looks like this :
const [currentCount, setCurrentCount] = React.useState(10);
const [intervalId, setIntervalId] = React.useState(10);
React.useEffect(() => {
const intervalId = setInterval(timer, 1000);
// store intervalId in the state so it can be accessed later:
setIntervalId(intervalId);
return () => {
clearInterval(intervalId);
};
}, []);
const timer = () => {
setCurrentCount((prev) => {
if (prev > 0) {
return prev - 1;
} else if (prev === 0) {
console.log("Still Runs");
clearInterval(intervalId);
return prev;
}
});
};
The value of currentCount decreases from 10 to 0 but I want to clear the interval when it reaches 0 and I tried to clear it with this piece of code clearInterval(intervalId)
but didn't work .
How can I clearInterval when the value of currentCount reaches 0 ?
CodePudding user response:
Your useEffect
hook is missing an important dependency from its dependency array: timer
. To make things simpler on yourself, you can move the timer
variable inside the effect (unless you have a good reason for it to be outside). This ends up having the added bonus that the timer
function will be able to reference the interval ID without maintaining it in state.
const [currentCount, setCurrentCount] = React.useState(10);
React.useEffect(() => {
const timer = () => {
setCurrentCount((prev) => {
if (prev > 0) {
return prev - 1;
} else if (prev === 0) {
console.log("Still Runs");
clearInterval(intervalId);
return prev;
}
});
};
const intervalId = setInterval(timer, 1000);
return () => {
clearInterval(intervalId);
};
}, []);