React Hooks实现计时器:15分钟后调用clearInterval停止计时方案咨询
解决方案1:在现有监听timer的useEffect中加入清除逻辑
直接在timer达到15分钟阈值的分支里,清空两个定时器即可,修改后代码如下:
useEffect(() => { if (timer < timeCeiling) { setMinutes(Math.floor(timer / 60)); setSeconds(timer % 60); } else { setMinutes(15); setSeconds(0); // 15分钟到点,清空两个定时器 clearInterval(countRef.current); clearInterval(lastUpdatedRef.current); // 可选:重置启停状态,避免后续操作异常 setIsActive(false); setIsPaused(false); } }, [timer]);
额外优化建议
- 新增组件卸载时的定时器清除逻辑,避免内存泄漏:
useEffect(() => { // 组件卸载时清空所有定时器 return () => { clearInterval(countRef.current); clearInterval(lastUpdatedRef.current); } }, []);
- 在
handleStart启动定时器前先清空旧定时器,避免用户多次点击启动生成多个无法追踪的定时器:
const handleStart = () => { // 先清除上一次启动的残留定时器 clearInterval(countRef.current); clearInterval(lastUpdatedRef.current); setIsActive(true); setIsPaused(true); countRef.current = setInterval(() => { setTimer((timer) => timer + 1); }, 1000); lastUpdatedRef.current = setInterval(() => { setLastUpdated(Date.now()); }, 30000); };
替代实现方案
如果不想把停止逻辑写在单独的useEffect里,也可以直接在计时定时器的回调中判断边界值,逻辑更内聚:
countRef.current = setInterval(() => { setTimer((timer) => { const newTimer = timer + 1; // 到达15分钟阈值直接停止 if (newTimer >= timeCeiling) { clearInterval(countRef.current); clearInterval(lastUpdatedRef.current); setIsActive(false); setIsPaused(false); } return newTimer; }); }, 1000);
内容的提问来源于stack exchange,提问作者clattenburg cake
相关产品推荐
相关产品推荐

