網頁倒數跳轉常見於下載頁、支付完成頁、維護通知頁。本文說明 setTimeout 與 setInterval 的差異,並提供完整可用範本。
// 執行一次
const timerId = setTimeout(callback, delayMs);
// 重複執行
const intervalId = setInterval(callback, intervalMs);
// 取消
clearTimeout(timerId);
clearInterval(intervalId);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>3 秒後跳轉</title>
<style>
body { font-family: sans-serif; text-align: center; padding-top: 50px; }
.countdown { color: #e74c3c; font-size: 2em; font-weight: bold; }
</style>
</head>
<body>
<h3>處理完成,<span class="countdown" id="counter">3</span> 秒後自動跳轉...</h3>
<p><a href="target.html" id="manualLink">若未跳轉請點這裡</a></p>
<script>
const targetUrl = 'target.html';
let seconds = 3;
const counter = document.getElementById('counter');
const link = document.getElementById('manualLink');
link.href = targetUrl;
const timer = setInterval(() => {
seconds--;
counter.textContent = seconds;
if (seconds <= 0) {
clearInterval(timer);
window.location.href = targetUrl;
}
}, 1000);
</script>
</body>
</html>
class RedirectCountdown {
constructor(url, seconds, options = {}) {
this.url = url;
this.seconds = seconds;
this.onTick = options.onTick || (() => {});
this.onComplete = options.onComplete || (() => {});
this.timer = null;
}
start() {
this.onTick(this.seconds);
this.timer = setInterval(() => {
this.seconds--;
this.onTick(this.seconds);
if (this.seconds <= 0) {
this.stop();
this.onComplete();
window.location.href = this.url;
}
}, 1000);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}
// 使用
const countdown = new RedirectCountdown('/dashboard', 5, {
onTick: (s) => document.getElementById('counter').textContent = s,
onComplete: () => console.log('跳轉中...')
});
// 用戶點擊取消按鈕
document.getElementById('cancelBtn').addEventListener('click', () => {
countdown.stop();
alert('已取消自動跳轉');
});
countdown.start();
| 問題 | 原因 | 解決 |
|---|---|---|
| 跳轉被瀏覽器攔截 | 非使用者主動觸發 | 改用 <a href="..."> 連結或 window.open(仍可能被攔截) |
| 倒數顯示不同步 | 主執行緒被阻塞 | 使用 requestAnimationFrame 或 Web Worker |
| 多次觸發跳轉 | 重複呼叫 setTimeout | 儲存 timerId,啟動前先 clearTimeout |
| 頁面卸載前需儲存狀態 | 跳轉即卸載 | 使用 navigator.sendBeacon() 或 beforeunload |
<head>
<meta http-equiv="refresh" content="5;url=https://example.com/target">
<!-- 5 秒後跳轉 -->
</head>
優點:JS 被禁用也能運作;缺點:無法互動控制、難以追蹤分析。
setTimeout,倒數顯示用 setInterval