萬盛學電腦網

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

JavaScript 定時關閉窗口倒計時實現

功能描述

頁面加載後啟動倒計時,顯示剩餘秒數,時間到自動關閉當前窗口。適用於提示頁、中間頁、自動跳轉關閉等場景。

完整代碼實例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>倒計時關閉窗口</title>
  <style>
    .countdown-box {
      width: 300px;
      height: 150px;
      margin: 100px auto;
      background: #f0f0f0;
      border: 1px solid #ddd;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-family: 'Microsoft YaHei', sans-serif;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .countdown-text {
      font-size: 18px;
      color: #333;
    }
    .countdown-num {
      font-size: 48px;
      font-weight: bold;
      color: #e74c3c;
      font-family: 'Arial', sans-serif;
    }
  </style>
</head>
<body>
  <div class="countdown-box">
    <div class="countdown-text">窗口將在</div>
    <div class="countdown-num" id="countdown">3</div>
    <div class="countdown-text">秒後自動關閉</div>
  </div>

  <script>
    (function() {
      var seconds = 3; // 倒計時秒數
      var $countdown = document.getElementById('countdown');
      
      function tick() {
        seconds--;
        $countdown.textContent = seconds;
        
        if (seconds <= 0) {
          // 嘗試關閉窗口
          // 注意:window.close() 僅能關閉由 window.open() 打開的窗口
          // 主窗口直接調用會被瀏覽器攔截或無效
          window.close(); 
        } else {
          setTimeout(tick, 1000);
        }
      }
      
      // 頁面加載後啟動
      window.onload = function() {
        tick();
      };
    })();
  </script>
</body>
</html>

關鍵點詳解

  1. 遞歸 setTimeout:使用 `setTimeout(tick, 1000)` 而非 `setInterval`,避免間隔累積誤差,且便於在條件滿足時停止。
  2. window.close() 限制:
    • 只能關閉由 `window.open()` 打開的窗口。
    • 用戶直接訪問的主窗口調用無效(現代瀏覽器安全策略)。
    • 若需關閉主窗口,可配合 `window.open('', '_self').close()` 嘗試,但不保證成功。
  3. 變量作用域:使用 IIFE(立即執行函數表達式)封裝變量,避免污染全局作用域。
  4. DOM 更新:直接操作 `textContent` 比 `innerHTML` 更安全、高效。

增強版:支持取消、暫停、自定義回調

function CountdownCloser(options) {
  var opts = Object.assign({
    seconds: 5,
    selector: '#countdown',
    onTick: null,       // 每秒回調 function(remaining)
    onClose: null,      // 關閉前回調
    closeMethod: 'auto' // 'auto' | 'openSelf' | 'none'
  }, options);
  
  var $el = document.querySelector(opts.selector);
  var timerId = null;
  var remaining = opts.seconds;
  
  function updateUI() {
    if ($el) $el.textContent = remaining;
  }
  
  function closeWindow() {
    if (opts.onClose) opts.onClose();
    if (opts.closeMethod === 'openSelf') {
      window.open('', '_self').close();
    } else if (opts.closeMethod === 'auto') {
      window.close();
    }
  }
  
  function tick() {
    remaining--;
    updateUI();
    if (opts.onTick) opts.onTick(remaining);
    
    if (remaining <= 0) {
      clearTimeout(timerId);
      closeWindow();
    } else {
      timerId = setTimeout(tick, 1000);
    }
  }
  
  this.start = function() {
    updateUI();
    timerId = setTimeout(tick, 1000);
  };
  
  this.stop = function() {
    clearTimeout(timerId);
  };
  
  this.reset = function(sec) {
    this.stop();
    remaining = sec || opts.seconds;
    this.start();
  };
}

// 使用
var closer = new CountdownCloser({
  seconds: 5,
  selector: '#countdown',
  onTick: function(s) { console.log('剩餘:', s); },
  onClose: function() { console.log('關閉了'); }
});
closer.start();

結語

定時關閉窗口看似簡單,但涉及瀏覽器安全策略、定時器選擇、變量作用域等細節。實際項目中建議封裝為可複用組件,並提供友好的用戶交互(如「取消關閉」按鈕)。

copyright © 萬盛學電腦網 all rights reserved