萬盛學電腦網

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

JavaScript 倒計時類實現:毫秒級精度、回調支援、自動銷毀

需求分析

  • 接收後端返回的剩餘秒數(remaintime)。
  • 客戶端每秒遞減顯示 HH:MM:SS。
  • 歸零時觸發回調(如提交表單、刷新頁面)。
  • 支援多實例、暫停/恢復、銷毀清理。

ES6 Class 完整實現

class CountdownTimer {
  /**
   * @param {Object} options
   * @param {string|HTMLElement} options.container - 容器選擇器或元素
   * @param {number} options.remaintime - 初始剩餘秒數
   * @param {Function} options.onTick - 每秒回調 (hours, minutes, seconds, totalSeconds)
   * @param {Function} options.onEnd - 倒計時結束回調
   * @param {boolean} options.autoStart - 是否自動開始
   */
  constructor(options = {}) {
    this.container = typeof options.container === 'string'
      ? document.querySelector(options.container)
      : options.container;
    if (!this.container) throw new Error('Container not found');

    this.remaintime = Math.max(0, Math.floor(options.remaintime)) || 0;
    this.onTick = options.onTick || (() => {});
    this.onEnd = options.onEnd || (() => {});
    this.timerId = null;
    this.isRunning = false;
    this.isPaused = false;
    this.startTime = 0;
    this.pausedRemaining = 0;

    // 預設 UI 渲染(可被 onTick 覆蓋)
    this.render = this.defaultRender.bind(this);

    if (options.autoStart !== false) this.start();
  }

  // 內部:計算時分秒
  _calc() {
    const h = Math.floor(this.remaintime / 3600);
    const m = Math.floor((this.remaintime % 3600) / 60);
    const s = this.remaintime % 60;
    return { h, m, s };
  }

  // 預設渲染:尋找容器內三個  或 data-role
  defaultRender({ h, m, s }) {
    const pad = n => String(n).padStart(2, '0');
    const $h = this.container.querySelector('[data-role="hour"], em:nth-child(1)');
    const $m = this.container.querySelector('[data-role="min"], em:nth-child(2)');
    const $s = this.container.querySelector('[data-role="sec"], em:nth-child(3)');
    if ($h) $h.textContent = pad(h);
    if ($m) $m.textContent = pad(m);
    if ($s) $s.textContent = pad(s);
  }

  // 核心計時循環
  _tick() {
    if (this.remaintime <= 0) {
      this.stop();
      this.onEnd.call(this);
      return;
    }
    this.remaintime--;
    const timeObj = this._calc();
    this.onTick(timeObj.h, timeObj.m, timeObj.s, this.remaintime);
    this.render(timeObj);
  }

  start() {
    if (this.isRunning) return;
    this.isRunning = true;
    this.isPaused = false;
    this.startTime = Date.now();
    this._tick(); // 立即執行一次
    this.timerId = setInterval(() => this._tick(), 1000);
  }

  pause() {
    if (!this.isRunning || this.isPaused) return;
    this.isPaused = true;
    clearInterval(this.timerId);
    this.timerId = null;
    this.pausedRemaining = this.remaintime;
  }

  resume() {
    if (!this.isRunning || !this.isPaused) return;
    this.isPaused = false;
    this.remaintime = this.pausedRemaining;
    this.startTime = Date.now();
    this._tick();
    this.timerId = setInterval(() => this._tick(), 1000);
  }

  stop() {
    if (this.timerId) clearInterval(this.timerId);
    this.timerId = null;
    this.isRunning = false;
    this.isPaused = false;
  }

  destroy() {
    this.stop();
    this.container = null;
    this.onTick = this.onEnd = null;
  }

  // 靜態工廠方法
  static create(container, seconds, callbacks) {
    return new CountdownTimer({ container, remaintime: seconds, ...callbacks });
  }
}

使用範例

<div id="timer">
  <span data-role="hour">00</span>:
  <span data-role="min">00</span>:
  <span data-role="sec">00</span>
</div>

<script>
const timer = new CountdownTimer({
  container: '#timer',
  remaintime: 10000, // 2 小時 46 分 40 秒
  onTick: (h, m, s, total) => {
    console.log(`剩餘 ${total} 秒`);
    // 最後 60 秒變紅
    if (total === 60) timer.container.style.color = 'red';
  },
  onEnd: () => {
    alert('時間到!');
    document.getElementById('timer').textContent = '已截止';
  }
});

// 手動控制範例
// timer.pause();
// timer.resume();
// timer.destroy();
</script>

進階:高精度防止漂移

使用 Date.now() 校準而非單純遞減:

_tick() {
  const now = Date.now();
  const elapsed = Math.floor((now - this.startTime) / 1000);
  this.remaintime = Math.max(0, this.initialRemaining - elapsed);
  // ... 後續同前
}

React/Vue 組件封裝提示

  • 使用 useRef/ref 持有實例。
  • onMounted 建立,onUnmounted 呼叫 destroy()。
  • 狀態同步:onTick 更新 ref 或 reactive 狀態觸發重渲染。
copyright © 萬盛學電腦網 all rights reserved