| API | 行為 | 回傳值 | 典型用途 |
|---|---|---|---|
setTimeout(fn, delay) | 延遲 delay 毫秒執行一次 fn | timerId (number) | 延遲執行、防抖、單次輪詢 |
setInterval(fn, interval) | 每間隔 interval 毫秒重複執行 fn | timerId (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);
比 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)setTimeout(obj.method, 1000) → 使用箭頭函數 setTimeout(() => obj.method(), 1000) 或 bindclearTimeout/clearInterval,防記憶體洩漏setTimeout(fn, 0) 實際約 4ms(HTML5 規範),不為 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 綁定與清理機制,是前端工程師處理非同步時序的核心基本功。