setInterval Drift Fixed By Self-Scheduling Timeouts
setInterval schedules each tick from the previous fire time, so loop delays accumulate into drift; self-scheduling setTimeout targets absolute boundaries.
Code
// 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();How it works
setInterval Drift Fixed By Self-Scheduling Timeouts keeps everything in the functions schedule, busyWork, driftWithSetInterval and alignedWithTimeout.
Repetition is confined to while (performance.now() < end) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Putting it to use
The main signature reads const schedule = ()
Output lines are prefixed (target last tick:, setInterval last tick:, aligned last tick:), making each step’s effect easy to spot.
Execute the file and main walks through driftWithSetInterval and alignedWithTimeout, in that order.
Core lines
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();
Interactive Tools for This Topic
FAQ
- What does setInterval Drift Fixed By Self-Scheduling Timeouts print when run?
- Invoke the file as-is — the `target last tick:`, `setInterval last tick:`, `aligned last tick:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.