JS 計時器是異步編程基石。本文系統講解 setTimeout、setInterval、requestAnimationFrame 的原理、差異、常見坑點、取消方法、節流防抖封裝與動畫循環最佳實踐。
var timerId = setTimeout(callback, delay, arg1, arg2, ...);
// timerId: 數字,唯一標識,用於 clearTimeout
// delay: 毫秒,最小 4ms(HTML5 規範),0 表示下一事件循環
// callback: 函數或字符串(不推薦字符串,類似 eval)
// 5 秒後彈窗
setTimeout(function() { alert('5 秒到了'); }, 5000);
// 傳參
setTimeout(function(name, age) { console.log(name, age); }, 1000, '張三', 25);
// 取消
var t = setTimeout(fn, 1000);
clearTimeout(t); // 在 1 秒內調用則 fn 不會執行
function repeat(fn, interval) {
fn();
setTimeout(function() { repeat(fn, interval); }, interval);
}
// 可隨時調整間隔、可在 fn 內決定是否繼續
var count = 0;
function tick() {
console.log(++count);
if (count < 10) setTimeout(tick, 1000);
}
tick();
var timerId = setInterval(callback, interval, arg1, arg2...);
// 返回 timerId,用於 clearInterval
setInterval(function() {
// 耗時 200ms 的任務
heavyTask();
}, 100); // 間隔 100ms
// 結果:任務堆積,瀏覽器可能併發執行或丟棄,導致不可控行為
// 遞歸 setTimeout:任務結束後再計時
function loop() {
heavyTask();
setTimeout(loop, 100); // 確保間隔至少 100ms
}
loop();
DOMHighResTimeStamp 參數(幀開始時間),便於計算增量。var startTime = null;
function animate(timestamp) {
if (!startTime) startTime = timestamp;
var progress = timestamp - startTime;
// 更新動畫狀態
var x = Math.min(progress / 1000 * 200, 200); // 1 秒移動 200px
element.style.transform = 'translateX(' + x + 'px)';
if (progress < 1000) {
requestAnimationFrame(animate); // 繼續下一幀
}
}
requestAnimationFrame(animate);
var rafId = requestAnimationFrame(animate);
cancelAnimationFrame(rafId);
function throttle(fn, delay) {
var last = 0;
return function(...args) {
var now = Date.now();
if (now - last >= delay) {
last = now;
fn.apply(this, args);
}
};
}
// 滾動事件節流
window.addEventListener('scroll', throttle(function() {
console.log('滾動中...', window.scrollY);
}, 200));
function debounce(fn, delay) {
var timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 輸入框防抖搜索
$('#search').on('input', debounce(function() {
var kw = $(this).val();
if (kw) searchAPI(kw);
}, 300));
setTimeout/Interval 最小間隔 1000ms(瀏覽器節能策略)。| API | 用途 | 精度 | 取消 | 推薦場景 |
|---|---|---|---|---|
| setTimeout | 一次性延遲 | ~4ms | clearTimeout | 延遲執行、遞歸替代 setInterval |
| setInterval | 固定間隔重複 | ~4ms | clearInterval | 簡輪詢、定時檢查(任務極快) |
| requestAnimationFrame | 幀同步動畫 | ~16.7ms | cancelAnimationFrame | JS 動畫、Canvas/WebGL、滾動特效 |
核心原則:能用 rAF 就不用 setInterval;長間隔/不精確用 setTimeout 遞歸;高頻事件必加節流/防抖。