精度和稳定性优先选 requestAnimationFrame,需用 performance.now() 计算剩余时间;setInterval 简单但易漂移,适合静态翻页;React 中应封装为可清理的自定义 Hook 并管理状态。

倒计时组件该用 setInterval 还是 requestAnimationFrame
精度和稳定性优先选 requestAnimationFrame,尤其在动画同步、帧率敏感场景下;setInterval 简单但容易漂移,比如 1000ms 间隔实际可能变成 1012ms 或 987ms,连跑 10 秒就差半秒以上。
实操建议:
-
requestAnimationFrame需自己记录起始时间,用performance.now()算已过毫秒数,再推算剩余秒数——更准,也避免定时器堆积 - 如果只是静态数字翻页(如“3…2…1…GO”),且不依赖帧同步,
setInterval足够,但务必用clearInterval及时销毁,否则倒计时结束还在跑 - 移动端要注意:部分安卓 WebView 在后台标签页会冻结
setInterval,而requestAnimationFrame直接停摆,此时得监听visibilitychange手动暂停/恢复
React 里实现可中断的倒计时 Hook 怎么写
不能直接在 useEffect 里裸写 setInterval,否则组件卸载后定时器还在跑,引发 Can't perform a React state update on an unmounted component 报错。
实操建议:
- 用
useRef存储定时器 ID 或animationFrameId,在 cleanup 函数里清除 - 倒计时状态建议拆成
remaining(数字)和status('idle'/'running'/'paused'/'finished'),方便外部控制 - 别把倒计时逻辑塞进 UI 组件里,抽成自定义 Hook,比如
useCountdown({ duration: 3000, onEnd: () => {...} }),参数显式、可测、易复用
示例关键片段:
function useCountdown({ duration, onEnd }) {
const [remaining, setRemaining] = useState(duration);
const [status, setStatus] = useState('idle');
const rafRef = useRef();
const startTimeRef = useRef();
const tick = () => {
const elapsed = performance.now() - startTimeRef.current;
const left = Math.max(0, duration - elapsed);
setRemaining(Math.ceil(left / 1000));
if (left <= 0) {
setStatus('finished');
onEnd?.();
return;
}
rafRef.current = requestAnimationFrame(tick);
};
const start = () => {
if (status !== 'idle' && status !== 'paused') return;
startTimeRef.current = performance.now() - (duration - remaining * 1000);
setStatus('running');
rafRef.current = requestAnimationFrame(tick);
};
useEffect(() => {
return () => cancelAnimationFrame(rafRef.current);
}, []);
return { remaining, status, start, pause: () => setStatus('paused'), reset: () => { ... } };
}
Canvas 渲染倒计时数字时字体模糊怎么办
Canvas 默认按设备像素比缩放后没做适配,文字边缘发虚,尤其在 Retina 屏或高 DPI 设备上明显。
实操建议:
- 获取真实像素比:
window.devicePixelRatio || 1,然后手动设置canvas.width和canvas.height为 CSS 尺寸 × 像素比 - 绘制前调用
ctx.scale(dpr, dpr),让所有坐标和字号按比例放大,再用ctx.font = 'bold 48px sans-serif'这类标准值,避免小数尺寸 - 别用
ctx.fillText直接居中,先用ctx.measureText算宽,再结合textAlign和textBaseline精确锚点,否则 iOS Safari 下“2”和“1”垂直位置不齐
倒计时结束后跳转页面,怎么避免用户反复点击触发多次
常见错误是把跳转逻辑写在按钮 onClick 里,而没关掉按钮或禁用交互,用户狂点就会发多个 location.href 或重复调用 history.push,造成白屏或路由异常。
实操建议:
- 倒计时结束瞬间,立即设按钮
disabled或加一层遮罩,同时清空所有定时器/动画帧 - 跳转前检查当前路由是否已是目标页,用
if (location.pathname !== '/game') location.replace('/game'),避免历史栈污染 - 如果走前端路由(如 React Router),用
navigate('/game', { replace: true }),而不是push,防止用户点返回又回到倒计时页再触发一次
倒计时看着简单,真正卡住人的往往是时机判断——什么时候该暂停、什么时候该重置、设备切后台后要不要续、网络延迟下服务端时间怎么对齐。这些细节不提前想清楚,上线后就是偶发性跳不过去的“3…2…1…”,卡在那一秒动不了。









