首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 實作自訂時間倒數/正計時器:從任意日期時間開始精準走時

     編輯:程式設計綜合問答

核心思路:時間差 + 定時器修正

瀏覽器 Date 物件只能取得「當前」時間。要實現從指定時間(如 2025-12-31 23:59:59)開始走動的時鐘,核心邏輯是:

  1. 計算 目標時間 與 當前系統時間 的毫秒差值(offset)。
  2. 每秒透過 setInterval 取得最新系統時間,加上 offset 得到「模擬時間」。
  3. 將模擬時間格式化顯示。

完整實作範例

class CustomClock {
  constructor(targetDateString) {
    // 1. 解析目標時間 (支援 ISO 8601 格式: "2025-12-31T23:59:59")
    this.targetTime = new Date(targetDateString).getTime();
    if (isNaN(this.targetTime)) throw new Error('Invalid date format');
    
    // 2. 計算初始偏移量
    this.offset = this.targetTime - Date.now();
    this.timerId = null;
  }

  start(selector) {
    const el = document.querySelector(selector);
    if (!el) return;

    const tick = () => {
      // 3. 每次取最新系統時間 + 固定偏移 = 模擬時間
      const simulated = new Date(Date.now() + this.offset);
      el.textContent = this.format(simulated);
    };

    tick(); // 立即顯示一次
    this.timerId = setInterval(tick, 1000);
  }

  stop() {
    if (this.timerId) clearInterval(this.timerId);
  }

  format(date) {
    const pad = n => String(n).padStart(2, '0');
    return `${date.getFullYear()}年${pad(date.getMonth()+1)}月${pad(date.getDate())}日 ` +
           `${pad(date.getHours())}時${pad(date.getMinutes())}分${pad(date.getSeconds())}秒`;
  }
}

// 使用範例
const clock = new CustomClock('2025-12-31T23:59:59');
clock.start('#clock-display');

關鍵細節補充

設定「任意時間」的完整參數

若不想用字串解析,可直接用 new Date(year, monthIndex, day, hour, minute, second):

// 注意:monthIndex 為 0-11 (0=一月)
const target = new Date(2025, 11, 31, 23, 59, 59); // 2025-12-31 23:59:59

精準度優化:校準系統時間漂移

長時間運行會有幾毫秒誤差,進階版可每分鐘透過 NTP 或伺服器 API 校準 offset。

倒數計時器變體

若需「倒數至目標時間」,邏輯改為 const diff = targetTime - Date.now(),判斷 diff <= 0 則停止並觸發回呼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved