重置间隔取决于布尔状态



如果模式布尔值为false,有什么方法可以重置此计时器吗?

我希望它只在模态出现时工作,并在模态关闭后立即重置。

useEffect(() => {
if (modal) {
const timer = setInterval(() => {
if (countRef.current >= 10) {
clearInterval(timer);
} else {
setCount((count) => count + 1);
}
}, 1000);
}
if (!modal) {
clear interval here and reset counter, is this possible?
}
}, [modal]);

您还必须存储间隔中的destroy函数。

// tsx
interface AppProps {
modal: boolean;
}
const App = ({ modal }: AppProps) => {
const intervalRef = useRef<ReturnType<typeof setInterval>>(null);
const countRef = useRef(0);
const setCount = (handler: (param: number) => number) =>
(countRef.current = handler(countRef.current));
useEffect(() => {
if (modal) {
intervalRef.current = setInterval(() => {
if (countRef.current >= 10) {
clearInterval(intervalRef.current);
} else {
setCount((count) => count + 1);
}
}, 1000);
}
if (!modal && intervalRef.current) {
clearInterval(intervalRef.current);
setCount((count) => count + 1);
}
return () => {
clearInterval(intervalRef.current);
}
}, [modal]);
return <div>hello</div>;
};
// jsx
const App = ({ modal }) => {
const intervalRef = useRef(null);
const countRef = useRef(0);
const setCount = (handler) =>
(countRef.current = handler(countRef.current));
useEffect(() => {
if (modal) {
intervalRef.current = setInterval(() => {
if (countRef.current >= 10) {
clearInterval(intervalRef.current);
} else {
setCount((count) => count + 1);
}
}, 1000);
}
if (!modal && intervalRef.current) {
clearInterval(intervalRef.current);
setCount((count) => count + 1);
}
return () => {
clearInterval(intervalRef.current);
}
}, [modal]);
return <div>hello</div>;
};

最新更新