Skip to content
jshacks.dev
Async

Timers in JavaScript Are Not Precise: Why and What to Do

Learn why setTimeout and setInterval fire late, how clamping and throttling affect them and how to build accurate clocks with performance.now.

7 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the JavaScript, Redis and Prometheus logos.

setTimeout(fn, 100) does not mean "run fn in 100 milliseconds". It means "run fn no sooner than 100 milliseconds from now, when the thread is free". The difference between those two sentences explains clocks that drift, animations that stutter, a countdown that finishes late and an interval that fires in bursts after a tab has been in the background. This post explains the causes on Node.js 24 and current browsers, with printed output: the thread is busy, the minimum delay is clamped, background tabs are throttled and the system clock itself moves. It then shows how to build timing that holds up, with performance.now, drift-correcting loops and deadlines, and when to avoid timers by using the right API for the job. The numbers that vary by machine are shown as comparisons, not exact timings.

A timer is a request to a queue

When you call setTimeout, the runtime records a due time and puts the callback in a timer queue. When the due time arrives, the callback becomes eligible to run, and it runs when the event loop is free to take it. Between "eligible" and "running" can be any amount of time, depending on what else is occupying the thread.

JavaScript
const start = performance.now();

setTimeout(() => {
  const waited = performance.now() - start;
  console.log("timer was due at 20 ms, ran late:", waited > 20);
}, 20);

const busyUntil = performance.now() + 60;
while (performance.now() < busyUntil) {
  // block the thread for 60 ms
}
Text
timer was due at 20 ms, ran late: true

The timer was due at 20 ms and ran after about 60, once the loop finished. Nothing is wrong with the timer. It was waiting for a thread that was busy. This is the main cause of lateness in real programs: other code on the same thread, such as a long synchronous function, a heavy render or a flood of microtasks.

The guarantee is a lower bound

The only promise is "not before". Even on an idle thread, the callback runs a little after the due time, because the timer implementation checks due timers at the start of each event loop iteration and the clock is read at millisecond resolution in Node.js.

JavaScript
const delays = [];

for (let i = 0; i < 5; i++) {
  const start = performance.now();
  await new Promise((resolve) => setTimeout(resolve, 10));
  delays.push(performance.now() - start);
}

console.log("never early:", delays.every((d) => d >= 9));
Text
never early: true

The threshold of 9 allows for clock rounding, since Node.js timers can report a delay that looks marginally under the requested one by rounding. In practice, you should expect the actual delay to be at least the request and typically one to a few milliseconds more.

Clamping

Minimum delay. Node.js treats a delay below 1 ms as 1 ms, and browsers have long clamped setTimeout(fn, 0) to a minimum of about 1 ms, with HTML's historical 4 ms clamp for timers nested more than five levels deep. Recursive setTimeout(fn, 0) loops in a browser therefore tick no faster than about every 4 ms.

Maximum delay. The delay is stored as a 32-bit signed integer, so the largest is 2,147,483,647 ms, about 24.8 days. Larger values overflow, and Node.js sets them to 1 ms with a warning.

JavaScript
const handle = setTimeout(() => console.log("fired"), 2 ** 31);

console.log("scheduled a timer past the limit");
clearTimeout(handle);
Text
scheduled a timer past the limit

Node.js prints a TimeoutOverflowWarning to stderr for that call. For long waits, store a due timestamp and check it periodically with a shorter timer.

Background tabs and power saving

Browsers throttle timers on pages the user cannot see. Chrome limits timers in background tabs to run at most once per second, and in tabs that have been hidden for a while it can slow them further, to once per minute for pages that meet certain criteria. Safari and Firefox apply their own limits. Battery saver modes add more. The consequence is that a setInterval(tick, 1000) countdown in a background tab does not reliably fire every second, and a clock that counts ticks drifts badly.

The fix is to never count ticks. Compare against a real time source.

JavaScript
function createCountdown(totalMs, onTick) {
  const deadline = performance.now() + totalMs;

  const timer = setInterval(() => {
    const remaining = Math.max(0, deadline - performance.now());
    onTick(remaining);
    if (remaining === 0) clearInterval(timer);
  }, 100);
}

createCountdown(250, (remaining) => {
  console.log("remaining under 300 ms:", remaining < 300);
});
Text
remaining under 300 ms: true
remaining under 300 ms: true
remaining under 300 ms: true

The display is derived from the deadline, so a late tick shows the right time anyway. When the tab returns to the foreground, the next tick catches up. This pattern, "timer for waking, clock for truth", is the central rule of accurate timing in JavaScript. Three lines print here because roughly three ticks fit into 250 ms at a 100 ms interval, plus or minus a tick.

Interval drift

setInterval(fn, 100) schedules the next run after the previous one starts, not after it ends, but each run is still subject to lateness, and lost ticks are not made up. A chain of setTimeout calls that each wait 100 ms drifts further, because each wait begins after the previous callback completes.

JavaScript
function driftingLoop(count, ms, done) {
  const start = performance.now();
  let n = 0;

  function tick() {
    n += 1;
    if (n === count) {
      const elapsed = performance.now() - start;
      done(elapsed >= count * ms);
    } else {
      setTimeout(tick, ms);
    }
  }

  setTimeout(tick, ms);
}

driftingLoop(5, 20, (atLeastNominal) => {
  console.log("total at least 100 ms, usually more:", atLeastNominal);
});
Text
total at least 100 ms, usually more: true

Five 20 ms waits in a row take at least 100 ms, and each added a little lateness, so the total grows. A self-correcting loop aims at absolute times, computing each wait from the deadline of the next tick.

JavaScript
function steadyLoop(count, ms, onTick, onDone) {
  const start = performance.now();
  let n = 0;

  function tick() {
    n += 1;
    onTick(n);

    if (n === count) {
      onDone(performance.now() - start);
      return;
    }

    const nextDue = start + (n + 1) * ms;
    setTimeout(tick, Math.max(0, nextDue - performance.now()));
  }

  setTimeout(tick, ms);
}

steadyLoop(5, 20, () => {}, (total) => {
  console.log("total close to 100 ms:", total >= 99 && total < 130);
});
Text
total close to 100 ms: true

If one tick runs 3 ms late, the next waits 3 ms less, so the error does not accumulate. The loop stays near the ideal schedule on average. The 130 bound is generous so that a busy machine does not fail the check.

Clocks: use the right one

Date.now() reads the system clock, which can jump forward or backward when the user changes the time, the machine syncs with a time server or a daylight saving switch applies. Measuring durations with it gives wrong answers when that happens. performance.now() reads a monotonic clock that never goes backward, with sub-millisecond resolution, and is the right tool for durations. Browsers deliberately coarsen its resolution, often to 100 microseconds or 1 millisecond, to limit timing attacks.

JavaScript
const t0 = performance.now();

let sum = 0;
for (let i = 0; i < 1e6; i++) sum += i;

const t1 = performance.now();
console.log("monotonic and non-negative:", t1 >= t0);
console.log("sum:", sum);
Text
monotonic and non-negative: true
sum: 499999500000

For a wall-clock time shown to people, use Date. For elapsed time, use performance.now(). For scheduling at a specific wall time, such as "run at midnight", compute the delay from the current Date and re-check when the timer fires, since a clock change can make it fire at the wrong moment.

Choosing a better API

Not everything that waits should use setTimeout.

You wantUse
Update visuals each framerequestAnimationFrame
Run once the browser is idlerequestIdleCallback or scheduler.postTask
Yield to input in a long jobscheduler.yield()
Run right after current codequeueMicrotask
Run after I/O in Node.jssetImmediate
Audio-accurate schedulingThe Web Audio clock, AudioContext.currentTime
A recurring job at set timesA scheduler outside the process (cron, queue)

Web Audio deserves a note, because musical timing needs precision that timers cannot give. The usual technique is a coarse setTimeout loop that looks a little ahead and schedules audio events against the sample-accurate audio clock. The same "timer to wake, precise clock to act" structure appears again.

Testing code that uses timers

Real waits make tests slow and flaky. Test runners offer fake timers that replace setTimeout, setInterval and Date, and let you advance time by hand. Node.js's own test runner has mock.timers, and Jest and Vitest have equivalents. Write the code so that the clock is an argument, which makes it testable without any of them, and test the lower-bound behavior, not exact timing.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.