React倒计时计时器无法停止,如何实现计时结束后显示0:00?
React 倒计时停止+结束显示0:00修改方案
你现有代码有两个核心问题:
- useEffect的依赖为空,无法感知倒计时是否结束,定时器会一直运行不会自动停止
- 没有对倒计时剩余时间做下限处理,时间到点后timeBetween会变成负数,显示异常。
具体修改点
- 给useEffect添加currentTime、targetTime作为依赖,每次时间更新后都能判断是否需要停止计时
- 计算timeBetween时增加下限判断,小于等于0时直接取值为0,确保后续计算的分钟、秒数都是0
- 在定时器逻辑里先判断剩余时间,已经到0就直接清除定时器,不再更新时间
修改后完整代码
// 剩余时间计算增加下限处理 const timeBetween = Math.max(targetTime - currentTime, 0); const seconds = Math.floor((timeBetween / 1000) % 60); const minutes = Math.floor((timeBetween / 1000 / 60) % 60); useEffect(() => { // 已经到结束时间直接不启动定时器 if (timeBetween <= 0) return; const interval = setInterval(() => { setCurrentTime(Date.now()); }, 1000); // 每次依赖变化、组件卸载时都清除旧定时器 return () => clearInterval(interval); }, [currentTime, targetTime]); // 新增依赖项 return ( <> <div className="content2"> <p style={{ color: "white" }}>We start in:</p> <p style={{ color: "white" }}> <span>{`${minutes}:${seconds < 10 ? "0" : ""}${seconds}`}</span> </p> </div> </> );
内容的提问来源于stack exchange,提问作者John G.
相关产品推荐
相关产品推荐

