[英]Javascript clearInterval with interval Id doesn't work in react js
I implemented a timer which works fine but the only problem is that it doesn't clearInterval when the timer ends.我实现了一个可以正常工作的计时器,但唯一的问题是计时器结束时它不会清除Interval。
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. currentCount 的值从 10 减小到 0,但我想在间隔达到 0 时清除它,我尝试用这段代码clearInterval(intervalId)
清除它,但没有奏效。
How can I clearInterval when the value of currentCount reaches 0? currentCount的值达到0时如何清除Interval?
Your useEffect
hook is missing an important dependency from its dependency array: timer
.您的useEffect
钩子缺少其依赖数组中的一个重要依赖项: 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).为了让您自己更简单,您可以将timer
变量移动到效果内部(除非您有充分的理由让它在外部)。 This ends up having the added bonus that the timer
function will be able to reference the interval ID without maintaining it in state.这最终获得了额外的好处,即timer
function 将能够引用间隔 ID,而无需在 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);
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.