萬盛學電腦網

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

JavaScript 定時跳轉頁面實作:setTimeout 應用指南

網頁倒數跳轉常見於下載頁、支付完成頁、維護通知頁。本文說明 setTimeout 與 setInterval 的差異,並提供完整可用範本。

核心 API

// 執行一次
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

替代方案:Meta Refresh(不需 JS)

<head>
    <meta http-equiv="refresh" content="5;url=https://example.com/target">
    <!-- 5 秒後跳轉 -->
</head>

優點:JS 被禁用也能運作;缺點:無法互動控制、難以追蹤分析。

總結

  • 簡單跳轉用 setTimeout,倒數顯示用 setInterval
  • 務必提供手動跳轉連結作為備援
  • 考慮使用者體驗:給予足夠閱讀時間、可取消、可見倒數
  • 現代專案建議封裝為可復用元件(Vue/React Component)
copyright © 萬盛學電腦網 all rights reserved