实现说明
setInterval 漂移与自调度对齐的核心是函数 schedule、busyWork、driftWithSetInterval、alignedWithTimeout。
这个文件只在 while (performance.now() < end) 里循环。异步部分依次 await 结果,顺序可预测。
使用要点
- 直接运行文件,输出会带上标签,比如
target last tick:、setInterval last tick:、aligned last tick:——输出的每一行都能指回产生它的那次调用。 main按顺序串起driftWithSetInterval、alignedWithTimeout;运行文件就会把这个流程跑一遍。
常见问题
运行「setInterval 漂移与自调度对齐」会打印什么?
运行文件本身,target last tick:、setInterval last tick:、aligned last tick: 这些前缀各对应一段演示逻辑。
主要签名是 const schedule = ()
核心语句
await new Promise((resolve) => {
let fired = 0;
const id = setInterval(() => {
fired += 1;
busyWork(10);
marks.push(performance.now() - start);
if (fired === TICKS) {
clearInterval(id);
resolve();
}
}, INTERVAL);
});
const intervalLast = await driftWithSetInterval();
const alignedLast = await alignedWithTimeout();
代码示例
// setInterval schedules the next tick from the previous fire time, so loop delays or scheduling jitter accumulate into drift;
// self-scheduling setTimeout aligns each tick to an absolute deadline, so jitter never accumulates
const INTERVAL = 100;
const TICKS = 5;
// Simulate ~10ms of real work per callback
function busyWork(ms) {
// Atomics.wait could block here, but it throws on a browser main thread;
// a plain busy loop blocks synchronously anywhere JS runs.
const end = performance.now() + ms;
while (performance.now() < end) {
// spin until ms have elapsed
}
}
async function driftWithSetInterval() {
const marks = [];
const start = performance.now();
await new Promise((resolve) => {
let fired = 0;
const id = setInterval(() => {
fired += 1;
busyWork(10);
marks.push(performance.now() - start);
if (fired === TICKS) {
clearInterval(id);
resolve();
}
}, INTERVAL);
});
return marks[TICKS - 1];
}
async function alignedWithTimeout() {
const marks = [];
const start = performance.now();
await new Promise((resolve) => {
let tick = 0;
const schedule = () => {
tick += 1;
const due = start + tick * INTERVAL; // target instant is independent of the previous actual fire
setTimeout(() => {
busyWork(10);
marks.push(performance.now() - start);
if (tick < TICKS) schedule();
else resolve();
}, Math.max(0, due - performance.now()));
};
schedule();
});
return marks[TICKS - 1];
}
async function main() {
const intervalLast = await driftWithSetInterval();
const alignedLast = await alignedWithTimeout();
const target = INTERVAL * TICKS;
console.log('target last tick:', target, 'ms');
console.log('setInterval last tick:', Math.round(intervalLast), 'ms (drift', Math.round(intervalLast - target), 'ms)');
console.log('aligned last tick:', Math.round(alignedLast), 'ms (drift', Math.round(alignedLast - target), 'ms)');
}
main();