需求:頁面載入後倒計時 60 秒,時間到自動 location.reload()。本文提供健壯的實現,修正原代碼的全局變量污染、重複定時器、內存洩漏等問題。
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>60 秒自動刷新示例</title>
<style>
#countdown { color: #0066cc; font-weight: 600; font-size: 1.2rem; }
</style>
</head>
<body>
<p>離下次刷新還有 <span id="countdown">60</span> 秒</p>
<script>
(() => {
const TOTAL = 60;
const el = document.getElementById('countdown');
let remaining = TOTAL;
let timerId = null;
function tick() {
remaining--;
el.textContent = remaining;
if (remaining <= 0) {
clearInterval(timerId);
location.reload();
}
}
// 頁面可見時才跑定時器,切換標籤頁暫停
function start() {
if (timerId) return;
timerId = setInterval(tick, 1000);
}
function stop() {
clearInterval(timerId);
timerId = null;
}
document.addEventListener('visibilitychange', () => {
document.hidden ? stop() : start();
});
// 頁面卸載清理
window.addEventListener('beforeunload', stop);
start();
})();
</script>
</body>
</html>
t、shua 污染全局。el.textContent 比 innerHTML 更安全、性能更好。function useCountdown(seconds, onEnd) {
const rem = ref(seconds);
let id = null;
const start = () => { if (id) return; id = setInterval(() => { rem.value--; if (rem.value <= 0) { clearInterval(id); id = null; onEnd?.(); } }, 1000); };
const stop = () => { clearInterval(id); id = null; };
onBeforeUnmount(stop);
onMounted(start);
return { rem, start, stop };
}
// Vue 3 使用
const { rem } = useCountdown(60, () => location.reload());
// 模板: {{ rem }} 秒
setInterval('shua()', 1000) 字符串形式等同 eval,嚴禁使用。clearInterval 導致多次刷新或內存洩漏。setTimeout 遞歸替代 setInterval,可動態調整間隔、避免堆積。// 遞歸 setTimeout 版(更靈活)
function countdown(sec) {
if (sec < 0) return location.reload();
el.textContent = sec;
setTimeout(() => countdown(sec - 1), 1000);
}
countdown(60);
掌握這些細節,能讓倒計時功能在生產環境穩定運行,不再成為「定時炸彈」。