萬盛學電腦網

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

JavaScript setTimeout 實現定時器與倒計時核心模式

基礎模式:遞歸 setTimeout(推薦)

比 setInterval 更精準,可動態調整間隔,避免執行時間導致的間隔偏移。

function startCounter() {
  var seconds = 0;
  var $display = $('#counter-display');
  
  function tick() {
    seconds++;
    $display.text(seconds + ' 秒');
    
    // 遞歸調用,形成循環
    timerId = setTimeout(tick, 1000);
  }
  
  var timerId = setTimeout(tick, 1000); // 啟動
  
  // 返回控制接口
  return {
    stop: function() { clearTimeout(timerId); },
    getSeconds: function() { return seconds; }
  };
}

// 使用
var counter = startCounter();
// 10 秒後停止
setTimeout(function() { counter.stop(); }, 10000);

進階模式:可暫停/恢復的計時器類

class Timer {
  constructor(interval = 1000) {
    this.interval = interval;
    this.elapsed = 0;
    this.timerId = null;
    this.startTime = null;
    this.callback = null;
  }
  
  start(callback) {
    this.callback = callback;
    this.startTime = Date.now() - this.elapsed;
    this._tick();
  }
  
  _tick() {
    this.elapsed = Date.now() - this.startTime;
    if (this.callback) this.callback(this.elapsed);
    this.timerId = setTimeout(() => this._tick(), this.interval);
  }
  
  pause() {
    if (this.timerId) {
      clearTimeout(this.timerId);
      this.timerId = null;
    }
  }
  
  resume() {
    if (!this.timerId) this._tick();
  }
  
  reset() {
    this.pause();
    this.elapsed = 0;
  }
  
  getFormattedTime() {
    var ms = this.elapsed;
    var s = Math.floor(ms / 1000) % 60;
    var m = Math.floor(ms / 60000) % 60;
    var h = Math.floor(ms / 3600000);
    return (h ? h + ':' : '') + 
           (m < 10 ? '0' : '') + m + ':' + 
           (s < 10 ? '0' : '') + s;
  }
}

// 使用示例
var timer = new Timer(100);
timer.start(function(elapsed) {
  $('#display').text(timer.getFormattedTime());
});

// 暫停/繼續按鈕
$('#pause-btn').click(function() { timer.pause(); });
$('#resume-btn').click(function() { timer.resume(); });
$('#reset-btn').click(function() { timer.reset(); $('#display').text('00:00'); });

倒計時組件實現

function Countdown(targetSeconds, options) {
  var opts = $.extend({
    onTick: null,      // 每秒回調(剩餘秒數)
    onEnd: null,       // 結束回調
    interval: 1000
  }, options);
  
  var remaining = targetSeconds;
  var timerId = null;
  
  function tick() {
    if (remaining <= 0) {
      clearTimeout(timerId);
      if (opts.onEnd) opts.onEnd();
      return;
    }
    
    if (opts.onTick) opts.onTick(remaining);
    remaining--;
    timerId = setTimeout(tick, opts.interval);
  }
  
  this.start = function() { tick(); };
  this.stop = function() { clearTimeout(timerId); };
  this.getRemaining = function() { return remaining; };
}

// 使用:60 秒倒計時
var cd = new Countdown(60, {
  onTick: function(sec) {
    $('#countdown').text(formatTime(sec));
  },
  onEnd: function() {
    alert('時間到!');
    $('#countdown').text('00:00');
  }
});
cd.start();

function formatTime(sec) {
  var m = Math.floor(sec / 60);
  var s = sec % 60;
  return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
}

setTimeout vs setInterval 核心差異

特性setTimeout 遞歸setInterval
間隔精度高(每次重新計算)低(固定排程,積累誤差)
動態調整間隔支持需 clear+set 重建
執行時間超過間隔順序執行,不重疊可能並行/丟幀
內存洩漏風險低(單一 timerId)高(易忘記 clearInterval)
適用場景動畫、倒計時、輪詢固定頻率輪詢、心跳

瀏覽器節流與 requestAnimationFrame

頁面隱藏/最小化時,瀏覽器會將 setTimeout 間隔限制在 1000ms+。動畫類場景請改用 requestAnimationFrame:

function smoothAnimation() {
  var start = performance.now();
  
  function frame(now) {
    var progress = Math.min((now - start) / 1000, 1); // 1秒動畫
    updateUI(progress);
    if (progress < 1) requestAnimationFrame(frame);
  }
  
  requestAnimationFrame(frame);
}
copyright © 萬盛學電腦網 all rights reserved