常見需求:操作成功後顯示提示訊息,N 秒後自動跳轉至指定頁面,並提供手動點擊連結以防跳轉失效。
<div id="msg">將在 <span id="countdown">3</span> 秒後跳轉...</div>
<a id="manualLink" href="target.html">立即跳轉</a>
<script>
var seconds = 3;
var url = 'target.html';
var $countdown = $('#countdown');
function tick() {
$countdown.text(seconds);
if (seconds <= 0) {
window.location.href = url;
return;
}
seconds--;
setTimeout(tick, 1000);
}
tick();
</script>
var delay = 5;
var timer = setInterval(function() {
$('#time').text(delay);
if (delay <= 0) {
clearInterval(timer);
window.location.href = 'https://example.com';
}
delay--;
}, 1000);
<p style="text-align:center; margin-top:50px;">
系統將在 <span id="time">5</span> 秒後自動跳轉,
若未跳轉請 <a href="https://jb51.net" id="manual">點擊這裡</a>。
</p>
<script>
var delay = 5;
var timer = setInterval(function() {
var $time = $('#time');
$time.text(delay);
if (delay <= 0) {
clearInterval(timer);
window.location.href = 'https://jb51.net';
}
delay--;
}, 1000);
// 頁面卸載時清除計時器(防記憶體洩漏)
window.addEventListener('beforeunload', function() { clearInterval(timer); });
</script>
class DelayedRedirect {
constructor(url, seconds, $countdownEl, $cancelBtn) {
this.url = url;
this.seconds = seconds;
this.$countdown = $countdownEl;
this.timer = null;
this.cancelled = false;
if ($cancelBtn) $cancelBtn.on('click', () => this.cancel());
}
start() {
this.tick();
}
tick() {
if (this.cancelled) return;
this.$countdown.text(this.seconds);
if (this.seconds <= 0) {
window.location.href = this.url;
return;
}
this.seconds--;
this.timer = setTimeout(() => this.tick(), 1000);
}
cancel() {
this.cancelled = true;
clearTimeout(this.timer);
this.$countdown.text('已取消');
}
}
// 使用
var redirect = new DelayedRedirect('target.html', 10, $('#countdown'), $('#cancelBtn'));
redirect.start();
clearInterval/clearTimeout 避免記憶體洩漏。