萬盛學電腦網

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

JavaScript 實作倒數計時自動跳轉頁面功能

應用場景

錯誤頁面、下載完成頁、驗證成功頁等,提示使用者 N 秒後自動導向首頁或指定頁面。

完整實作範例

<!DOCTYPE html>
<html>
<head>
<title>系統錯誤 - 即將跳轉</title>
<link rel="stylesheet" href="css/login1.css" />
<script type="text/javascript">
var countdown = 5; // 倒數秒數
var timerId;

window.onload = function() {
  timerId = setInterval(updateCountdown, 1000);
};

function updateCountdown() {
  if (countdown === 0) {
    clearInterval(timerId);
    window.location.href = '../index.html'; // 跳轉目標
    return;
  }
  document.getElementById('mes').innerHTML = countdown;
  countdown--;
}
</script>
</head>
<body>
<div id="errorfrm">
  <h3>出錯啦~~~</h3>
  <div id="error">
    <img src="images/error.gif" alt="錯誤圖示" />
    <p>系統發生錯誤,請聯繫管理員!</p>
    <p>將在 <span id="mes">5</span> 秒後自動返回首頁!</p>
  </div>
</div>
</body>
</html>

關鍵點解析

  1. setInterval(fn, 1000):每秒執行一次更新倒數顯示。
  2. clearInterval(timerId):倒數歸零時清除定時器,避免記憶體洩漏。
  3. window.location.href = url:執行頁面跳轉。
  4. window.onload 確保 DOM 就緒後再啟動定時器。

進階版:可取消、暫停/繼續、顯示進度條

var CountdownRedirect = {
  seconds: 10,
  timer: null,
  url: '/home',
  $el: null,
  
  start: function(selector, targetUrl, secs) {
    this.$el = $(selector);
    this.url = targetUrl;
    this.seconds = secs || 10;
    this.render();
    this.timer = setInterval(() => this.tick(), 1000);
    return this;
  },
  
  tick: function() {
    this.seconds--;
    this.$el.find('.countdown-num').text(this.seconds);
    this.$el.find('.progress-bar').css('width', (this.seconds/this.initial*100) + '%');
    if (this.seconds <= 0) this.redirect();
  },
  
  redirect: function() {
    clearInterval(this.timer);
    window.location.href = this.url;
  },
  
  pause: function() { clearInterval(this.timer); },
  resume: function() { this.timer = setInterval(() => this.tick(), 1000); },
  
  render: function() {
    this.initial = this.seconds;
    this.$el.html(`
      <p>${this.seconds} 秒後自動跳轉... <span class="countdown-num">${this.seconds}</span></p>
      <div class="progress"><div class="progress-bar"></div></div>
      <button onclick="CountdownRedirect.pause()">暫停</button>
    `);
  }
};

// 使用
CountdownRedirect.start('#redirect-box', '/dashboard', 10);

基本版滿足簡單需求,進階版適合需使用者互動控制的場景。

copyright © 萬盛學電腦網 all rights reserved