【发布时间】:2021-12-30 17:04:21
【问题描述】:
我实现了一个可以正常工作的计时器,但唯一的问题是计时器结束时它不会清除Interval。
我的代码如下所示:
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;
}
});
};
currentCount 的值从 10 减少到 0,但我想在它达到 0 时清除间隔,我试图用这段代码 clearInterval(intervalId) 清除它,但没有奏效。
currentCount的值达到0时如何清除Interval?
【问题讨论】:
-
你为什么要在第 1 行再次调用 setInterval。 4 ?在 1 Line 中声明 setInterval 时完成.... [考虑表单 useEffect ! ]
-
考虑一下这个小vanila js fiddle
标签: javascript reactjs setinterval clearinterval