遊戲循環、輪播圖、模擬人類行為測試等場景,常需「不固定間隔」重複執行函數。本文解析遞迴 setTimeout 實現隨機間隔的模式,對比 setInterval 差異,並提供可復用的工具函數。
function randRange(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function toggleSomething() {
// 業務邏輯:切換元素可見性
document.getElementById('box').classList.toggle('visible');
// 從預設間隔池隨機抽取下一次間隔
var intervals = [200, 300, 150, 250, 2000, 3000, 1000, 1500];
var nextDelay = randRange(intervals);
// 遞迴排程下一次
setTimeout(toggleSomething, nextDelay);
}
// 啟動
setTimeout(toggleSomething, 1000); // 初始延遲 1 秒
setInterval?// setInterval 固定間隔,無法動態改變
var timer = setInterval(toggleSomething, 1000);
// 若想改間隔,必須 clearInterval 再重新 setInterval,麻煩且易漏
// 遞迴 setTimeout 靈活控制每次間隔
function scheduleNext() {
var delay = calculateDynamicDelay(); // 可根據狀態、負載、隨機決定
setTimeout(function() {
doWork();
scheduleNext(); // 遞迴
}, delay);
}
class RandomInterval {
constructor(task, intervalOptions = {}) {
this.task = task;
this.intervals = intervalOptions.intervals || [1000];
this.min = intervalOptions.min || 0;
this.max = intervalOptions.max || Infinity;
this.timer = null;
this.running = false;
}
start(initialDelay = 0) {
if (this.running) return;
this.running = true;
this.timer = setTimeout(() => this._tick(), initialDelay);
}
stop() {
if (this.timer) clearTimeout(this.timer);
this.running = false;
}
_tick() {
if (!this.running) return;
try {
this.task();
} catch (e) {
console.error('RandomInterval task error:', e);
}
// 計算下一次間隔
let delay;
if (this.intervals.length) {
delay = this.intervals[Math.floor(Math.random() * this.intervals.length)];
} else {
delay = this.min + Math.random() * (this.max - this.min);
}
// 限制範圍
delay = Math.max(this.min, Math.min(this.max, delay));
this.timer = setTimeout(() => this._tick(), delay);
}
}
// 使用範例
const blinker = new RandomInterval(
() => document.getElementById('box').classList.toggle('visible'),
{ intervals: [200, 300, 150, 250, 1000, 2000] }
);
blinker.start(1000);
// 頁面卸載時清理
window.addEventListener('beforeunload', () => blinker.stop());
clearTimeout,否則記憶體洩漏。seedrandom 庫)。遞迴 setTimeout 是實現動態、隨機、可控間隔任務的標準模式,掌握它能讓你的定時邏輯更靈活自然。