萬盛學電腦網

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

JavaScript 定時器完整指南:setTimeout、setInterval 與實戰模式

兩大核心 API

API行為回傳值典型用途
setTimeout(fn, delay)延遲 delay 毫秒執行一次 fntimerId (number)延遲執行、防抖、單次輪詢
setInterval(fn, interval)每間隔 interval 毫秒重複執行 fntimerId (number)輪詢、動畫、定時刷新

基礎範例:延遲與週期執行

// 延遲 3 秒彈窗
var timerId = setTimeout(function() {
  alert('延遲 3 秒成功');
}, 3000);

// 取消延遲
clearTimeout(timerId);

// 每秒更新計數器
var counter = 0;
var intervalId = setInterval(function() {
  counter++;
  document.getElementById('counter').textContent = counter;
  if (counter >= 10) {
    clearInterval(intervalId);
    alert('達到 10 秒');
  }
}, 1000);

進階模式一:可暫停/繼續的定時器

var PausableTimer = (function() {
  function PausableTimer(fn, interval) {
    this.fn = fn;
    this.interval = interval;
    this.timerId = null;
    this.remaining = 0;
    this.startTime = 0;
  }

  PausableTimer.prototype.start = function() {
    this.startTime = Date.now();
    this.timerId = setInterval(this.fn, this.interval);
  };

  PausableTimer.prototype.pause = function() {
    if (this.timerId) {
      clearInterval(this.timerId);
      this.remaining = this.interval - (Date.now() - this.startTime);
      this.timerId = null;
    }
  };

  PausableTimer.prototype.resume = function() {
    if (!this.timerId) {
      // 先執行一次補上剩餘時間
      setTimeout(this.fn, this.remaining);
      this.timerId = setInterval(this.fn, this.interval);
    }
  };

  PausableTimer.prototype.stop = function() {
    if (this.timerId) {
      clearInterval(this.timerId);
      this.timerId = null;
      this.remaining = 0;
    }
  };

  return PausableTimer;
})();

// 使用
var timer = new PausableTimer(function() { console.log('tick'); }, 1000);
timer.start();
setTimeout(function() { timer.pause(); }, 3500);
setTimeout(function() { timer.resume(); }, 5500);

進階模式二:requestAnimationFrame 動畫迴圈

比 setInterval 更平滑、省電、自動暫停背景頁籤:

function animate(fn) {
  var lastTime = 0;
  function loop(time) {
    var delta = time - lastTime;
    lastTime = time;
    fn(delta);
    requestAnimationFrame(loop);
  }
  requestAnimationFrame(loop);
}

// 使用:每秒更新一次(自動節流)
var lastLog = 0;
animate(function(delta) {
  lastLog += delta;
  if (lastLog >= 1000) {
    console.log('1 秒過去');
    lastLog = 0;
  }
});

進階模式三:防抖與節流

// 防抖:連續觸發只執行最後一次
function debounce(fn, wait) {
  var timer = null;
  return function() {
    var ctx = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(ctx, args);
    }, wait);
  };
}

// 節流:固定頻率執行
function throttle(fn, limit) {
  var inThrottle = false;
  return function() {
    var ctx = this, args = arguments;
    if (!inThrottle) {
      fn.apply(ctx, args);
      inThrottle = true;
      setTimeout(function() { inThrottle = false; }, limit);
    }
  };
}

// 實戰:搜尋框防抖
$('#search').on('input', debounce(function() {
  doSearch(this.value);
}, 300));

// 實戰:滾動事件節流
$(window).on('scroll', throttle(function() {
  checkLazyLoad();
}, 200));

常見陷阱與最佳實踐

  • 字串參數已棄用:setTimeout('func()', 1000) → 改用函數引用setTimeout(func, 1000)
  • this 綁定丟失:setTimeout(obj.method, 1000) → 使用箭頭函數 setTimeout(() => obj.method(), 1000) 或 bind
  • 清理 timerId:組件銷毀、頁面卸載時務必 clearTimeout/clearInterval,防記憶體洩漏
  • 最小延遲:現代瀏覽器 setTimeout(fn, 0) 實際約 4ms(HTML5 規範),不為 0
  • 避免巢狀 setTimeout 替代 setInterval:誤差會累積,長時間運行偏移嚴重

現代替代:Web Workers 與 setTimeout 0

// 耗時計算移至 Worker,主執行緒不阻塞
var worker = new Worker('calc.js');
worker.postMessage(data);
worker.onmessage = function(e) { console.log(e.data); };

// setTimeout 0:推到下一個事件循環(微任務後)
setTimeout(function() {
  console.log('這在所有同步代碼、Promise 之後執行');
}, 0);

總結

掌握 setTimeout/setInterval 核心機制,熟練實作暫停/繼續、防抖/節流、動畫迴圈等模式,並注意 this 綁定與清理機制,是前端工程師處理非同步時序的核心基本功。

copyright © 萬盛學電腦網 all rights reserved