🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Browser Timers, Frames, and the Microtask Queue

Web FoundationsPerformanceđŸŸĸ Free Lesson

Timers, Frames, and the Microtask Queue

JavaScript in the browser runs on one thread, and that thread is shared between your code, style calculation, painting, and input handling. Everything that looks concurrent is a scheduling decision made on your behalf: work is placed on a queue, the current job finishes, and the next job starts. Understanding the three queues involved is the difference between code that feels instant and code that stutters at the worst possible moment.

The task queue, sometimes called the macrotask queue, holds timers, network callbacks, click handlers, and message events. The microtask queue holds promise callbacks and mutation observer callbacks, and it drains completely after every task before the browser is allowed to paint or handle the next event. A fourth path, the animation frame callback queue, is consulted once per display refresh and is the only queue guaranteed to run immediately before a repaint.

The practical consequences follow directly from those rules:

  • a promise callback always runs before a zero-millisecond timeout from the same turn of the script
  • the microtask queue has no time limit, so an infinitely resolving promise starves rendering entirely
  • timers are a lower bound, never an exact delay, and they lengthen when the main thread is busy
  • animation frame callbacks are skipped when the tab is hidden, which makes them the right home for visual work

The Order Script Actually Executes In

Rather than memorise the rules, run them. The snippet below writes a numbered trace to the page, and reading the output once teaches the ordering better than any diagram.

<p id="trace"></p>
<button id="run">Run the trace</button>

<script>
const lines = [];
const record = (label) => lines.push(label);
const flush = () => {
  document.getElementById('trace').textContent = lines.join(' | ');
};

document.getElementById('run').addEventListener('click', () => {
  lines.length = 0;

  record('1 sync start');

  setTimeout(() => {
    record('8 timeout 0ms');
    flush();
  }, 0);

  Promise.resolve()
    .then(() => record('4 microtask from resolved promise'))
    .then(() => record('5 chained microtask'));

  queueMicrotask(() => record('6 queueMicrotask'));

  requestAnimationFrame(() => record('7 animation frame'));

  record('2 sync end');
});
</script>

The trace reads 1, 2, 4, 5, 6, 7, 8. Synchronous code finishes first because nothing can interrupt it. Every microtask drains next, including the ones created during draining, which is why 5 follows 4 without a yield. The frame callback lands before the timer because it is tied to the next repaint rather than to a clock, and the timeout comes last since even a zero delay is deferred to the end of the queue.

âš ī¸A microtask cannot yield

Because the microtask queue drains to exhaustion, scheduling work recursively from a promise callback blocks painting until the stack is empty. When a chain is long, break it with a timeout or an animation frame so the browser gets a chance to respond to input.

Choosing Between the Available Schedulers

Each scheduler answers a different question, and picking the wrong one produces bugs that look like design flaws but are really timing bugs.

SchedulerFiresBest forSkipped in background tabsTypical misuse
setTimeout(fn, 0)At least 0 ms after the current taskDeferring work past the current turnNo, but clamped to about 1000 msAssuming it is a 0 ms delay
setIntervalRepeatedly on a fixed cadencePolling a resource you must re-checkNo, throttledAnimation, where drift accumulates
requestAnimationFrameBefore the next repaintAnything visualYesLong computation inside the callback
queueMicrotaskImmediately after the current taskConsistent state before the next taskNoWork that should be interruptible
MessageChannelOn the next port messageYielding without the 4 ms clamp that nested timeouts acquireNoSimple cases a timeout already handles

The clamp on nested timeouts is a detail worth knowing: once you have a chain of zero-delay timeouts, the browser enforces a minimum gap of roughly four milliseconds, which is why a recursive timeout loop runs at about 250 iterations per second rather than unbounded speed.

Debounce and Throttle, Implemented Once

Almost every interaction handler on a page needs one of two shapes. Debounce collapses a burst of events into a single call after the burst stops, which suits search input and autosave. Throttle guarantees a call at most once per interval, which suits scroll position and pointer tracking where you want a steady stream rather than silence until the user stops.

javascript
function debounce(fn, wait = 250) {
  let timer = null;
  return function debounced(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), wait);
  };
}

function throttle(fn, limit = 100) {
  let last = 0;
  let pending = null;
  return function throttled(...args) {
    const now = Date.now();
    const remaining = limit - (now - last);

    if (remaining <= 0) {
      clearTimeout(pending);
      last = now;
      fn.apply(this, args);
    } else if (!pending) {
      pending = setTimeout(() => {
        last = Date.now();
        pending = null;
        fn.apply(this, args);
      }, remaining);
    }
  };
}

const search = debounce((query) => {
  document.getElementById('results').dataset.query = query;
  runSearch(query);
}, 300);

const onScroll = throttle(() => {
  document.getElementById('bar').dataset.offset = String(window.scrollY);
}, 100);

document.querySelector('input[type="search"]')
  .addEventListener('input', (event) => search(event.target.value));

window.addEventListener('scroll', () => onScroll(), { passive: true });

The trailing branch inside throttle is what separates a correct implementation from the common one-liner. Without it, the final event of a burst is dropped, so a scroll that ends between two intervals never reports its last position. The passive: true option on the scroll listener is the other half: it tells the browser the handler will never call preventDefault, so scrolling can begin on a separate compositor thread instead of waiting for your callback.

requestAnimationFrame and the Frame Budget

A 60 Hz display gives you about 16.7 milliseconds per frame, and that budget covers your JavaScript, style recalculation, layout, and paint. Animation frame callbacks are the only scheduling primitive aligned with that rhythm, which is why anything that moves should start there and why a timer-driven animation visibly tears on high-refresh displays.

Two rules keep frames cheap. First, read and write layout in separate passes; reading offsetHeight after writing a style forces an immediate synchronous layout inside the callback, and doing that in a loop is the classic source of jank. Second, keep the callback itself short. If a frame's work does not fit, move the computation to a worker and apply the result in the next frame.

Why setInterval Drifts, and What to Do Instead

setInterval schedules the next call relative to when the previous call should have fired, not when it did. A callback that runs for forty milliseconds on a fifty-millisecond interval will queue behind itself, and since timers do not stack, the browser simply drops the missed invocations and the perceived cadence slips. Paused background tabs make it worse by throttling the interval dramatically, so a one-second poll can arrive minutes later with no indication that anything was missed.

The robust replacement is a self-scheduling timeout that measures elapsed time from a fixed anchor.

javascript
function scheduleEvery(targetMs, job) {
  let start = performance.now();

  const tick = () => {
    const drift = performance.now() - start;
    job(drift);
    start += targetMs;
    const delay = Math.max(0, start - performance.now());
    setTimeout(tick, delay);
  };

  setTimeout(tick, targetMs);
}

const stop = scheduleEvery(1000, (drift) => {
  console.log(`tick, ${Math.round(drift)} ms since anchor`);
});

Because the anchor advances by the intended interval rather than by the observed one, late ticks correct themselves instead of accumulating, and a long pause produces one catch-up tick rather than a burst of queued calls.

Keeping Long Work Off the Main Thread

Timers, frames, and microtasks all run on the same thread that has to answer clicks within one hundred milliseconds, so no amount of scheduling finesse helps if a single job takes four hundred. Work that exceeds a few milliseconds belongs in a Web Worker, which returns results through a message event that lands on the task queue like any other callback.

The pattern that ties everything together is a small scheduler: run fast work synchronously, defer medium work with a timeout, animate with a frame callback, and ship heavy work to a worker. Pages built that way stay responsive because the main thread is never asked to do anything that cannot be interrupted at a boundary.

Common Mistakes

Using setTimeout(fn, 0) and expecting true concurrency

Fix: Remember that the main thread is single and the callback is queued; use queueMicrotask for immediate continuation and a worker for parallelism.

Driving animation from setInterval

Fix: Use requestAnimationFrame so the update lands exactly before a repaint and pauses in background tabs.

Writing a debounce that drops the final trailing call

Fix: Clear and restart the timer on every event so the last one always fires after the quiet period.

Doing layout reads and style writes in the same loop

Fix: Batch all reads, then all writes, so the browser performs one layout instead of forcing one on every iteration.

Key Takeaways

  • Microtasks drain to exhaustion after every task, before the browser may paint, which is why promise callbacks beat zero-delay timers.
  • Timers are lower bounds and drift with load; animation frames are the only scheduler tied to the display.
  • Debounce waits for silence; throttle enforces a steady interval and must handle its trailing call.
  • A frame budget is about 16.7 milliseconds and includes layout and paint, not just your JavaScript.
  • Anything that consistently exceeds a few milliseconds belongs in a worker, where it cannot block input.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement