萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 延遲跳轉頁面:倒數計時與自動導向實作

常見需求:操作成功後顯示提示訊息,N 秒後自動跳轉至指定頁面,並提供手動點擊連結以防跳轉失效。

方法一:setTimeout 遞迴更新倒數


<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>

方法二:setInterval 週期性更新


var delay = 5;
var timer = setInterval(function() {
    $('#time').text(delay);
    if (delay <= 0) {
        clearInterval(timer);
        window.location.href = 'https://example.com';
    }
    delay--;
}, 1000);

完整 HTML 範例(含手動連結 fallback)


<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 避免記憶體洩漏。
  • 提供明顯的手動連結,尊重使用者控制權。
  • SEO 頁面避免使用 Meta Refresh 或 JS 跳轉,影響搜尋引擎判斷。
copyright © 萬盛學電腦網 all rights reserved