Skip to content
jshacks.dev
Async

queueMicrotask vs setTimeout vs setImmediate

Compare queueMicrotask, setTimeout and setImmediate on Node.js 24, see the order they run in and learn which one to pick for deferring work.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, TypeScript, npm, Node.js and Vite logos.

Three functions defer a piece of code until later, and they defer it by very different amounts. queueMicrotask runs the function as soon as the current code finishes, before anything else. setImmediate runs it after the current round of I/O. setTimeout runs it after a delay measured in milliseconds, and never sooner than the next timers phase. Picking the wrong one produces bugs that look like timing luck: a callback that starves a page, a test that passes on one machine only, a race between I/O and a timer that flips with system load. This post compares the three on Node.js 24 with printed output, explains the one ordering that is not deterministic, and gives a rule of thumb for each use. Browser behavior is noted where it differs, since setImmediate does not exist there.

What each one does

FunctionRunsQueueWhere available
queueMicrotask(fn)After the current stack empties, before any macrotaskMicrotask queueNode.js and browsers
setTimeout(fn, ms)In the timers phase, once ms have passedTimer queueNode.js and browsers
setImmediate(fn)In the check phase, right after the poll phaseCheck queueNode.js (and old browsers)

The first is a microtask, the other two are macrotasks. As the microtask post explains, all microtasks run before the next macrotask.

The ordering that is guaranteed

In a CommonJS file:

JavaScript
setTimeout(() => console.log("setTimeout"), 0);
setImmediate(() => console.log("setImmediate"));
queueMicrotask(() => console.log("queueMicrotask"));
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));

console.log("sync");
Text
sync
nextTick
queueMicrotask
promise
setTimeout
setImmediate

In this main-script case, the final two lines can appear in either order, which the next section explains. The first four are guaranteed. The synchronous line prints first. In CommonJS, process.nextTick runs before promise microtasks (in an ES module's main body the promise callbacks go first), and queueMicrotask and the promise callback run in the order they were queued, which here is queueMicrotask first. The macrotasks follow.

The order that is not guaranteed

Called from the main module, setTimeout(fn, 0) and setImmediate(fn) can run in either order, because it depends on whether one millisecond has elapsed by the time the loop starts. The timer has a minimum delay of 1 ms, so a fast start prints setImmediate first, and a slower one prints setTimeout first. Do not write code that depends on it.

Inside an I/O callback, the order is fixed. The loop is in the poll phase, and the next phase is check, where setImmediate runs, before the loop returns to timers.

JavaScript
import { readFile } from "node:fs";

readFile("package.json", () => {
  setTimeout(() => console.log("setTimeout"), 0);
  setImmediate(() => console.log("setImmediate"));
});
Text
setImmediate
setTimeout

The script assumes a package.json exists in the working directory. Here setImmediate always wins. That is the reason setImmediate exists: to run something right after the current I/O, without a delay and without guessing.

queueMicrotask: finish this before anything else happens

Use it when the function must run after the current synchronous code and before the runtime does anything else, including I/O and rendering. Typical reasons are to make an API consistently asynchronous or to batch several synchronous updates into one.

JavaScript
const pending = new Set();
let flushQueued = false;

function update(name) {
  pending.add(name);

  if (!flushQueued) {
    flushQueued = true;
    queueMicrotask(() => {
      console.log("flushing", [...pending]);
      pending.clear();
      flushQueued = false;
    });
  }
}

update("title");
update("body");
update("footer");
console.log("updates requested");
Text
updates requested
flushing [ 'title', 'body', 'footer' ]

Three calls made one flush. That pattern, schedule once and collect, is how many frameworks batch changes. The danger is the starvation described earlier: a microtask that requeues itself blocks all macrotasks.

setTimeout: wait at least this long

Use it for real delays, and for yielding to I/O and rendering. setTimeout(fn, 0) is the common way to say "run after everything else due". Two limits apply. The delay is a minimum, not a promise, since the callback waits for the thread to be free. And Node.js clamps delays below 1 ms to 1 ms.

JavaScript
const start = Date.now();

setTimeout(() => {
  const elapsed = Date.now() - start;
  console.log("waited at least 50 ms:", elapsed >= 49);
}, 50);

const busyUntil = Date.now() + 80;
while (Date.now() < busyUntil) {
  // block for 80 ms
}
Text
waited at least 50 ms: true

The callback was due at 50 ms and ran after about 80, once the busy loop finished. A timer says "not before", never "exactly at". In browsers, nested timers and background tabs are throttled further, with a minimum of 4 ms for nested calls and a coarser rate for hidden tabs.

setImmediate: after I/O, without a timer

Use it on Node.js when you want to give I/O a turn, then continue, and you do not care about a time. It is the right tool for splitting a long job into chunks, because after each chunk the loop can handle sockets and files before the next one.

JavaScript
function processInChunks(items, handle, done) {
  let index = 0;

  function runChunk() {
    const end = Math.min(index + 2, items.length);

    for (; index < end; index++) handle(items[index]);

    if (index < items.length) setImmediate(runChunk);
    else done();
  }

  runChunk();
}

processInChunks([1, 2, 3, 4, 5], (n) => console.log("item", n), () => console.log("all done"));
Text
item 1
item 2
item 3
item 4
item 5
all done

Between each pair of items, the event loop could service other work, so a long list does not freeze the server. Chunk size controls the trade: larger chunks finish sooner, and smaller ones keep the loop more responsive. A setTimeout(runChunk, 0) would work too, with the 1 ms minimum added per chunk, which is why setImmediate is preferred on Node.js. In a browser, use scheduler.yield() or setTimeout.

Which to choose

You want toUse
Run right after the current code, before anything elsequeueMicrotask
Make a sometimes-sync API always asyncqueueMicrotask
Batch several synchronous calls into one flushqueueMicrotask
Run after pending I/O, no delay (Node.js)setImmediate
Break a long CPU job into chunks (Node.js)setImmediate
Wait a real amount of timesetTimeout
Yield in a browser so the page can paintsetTimeout or scheduler.yield()

A good default is to reach for the most local one first. If a microtask is enough, use it. If you need the loop to breathe, use a macrotask.

Cancelling

setTimeout and setImmediate return handles you can cancel with clearTimeout and clearImmediate. queueMicrotask returns nothing and cannot be cancelled, so guard with a flag if the work might become unnecessary.

JavaScript
const handle = setImmediate(() => console.log("never printed"));
clearImmediate(handle);

let cancelled = false;
queueMicrotask(() => {
  if (!cancelled) console.log("not printed either");
});
cancelled = true;

console.log("done");
Text
done

A note on testing these

Tests that depend on the order of setTimeout and setImmediate from the main script are flaky by nature, because the order depends on process start time. If you need a deterministic order in a test, put both calls inside an I/O callback, or avoid depending on it at all. For code that uses queueMicrotask, tests are deterministic, and you can assert the order against promise callbacks directly. When a test must wait for a macrotask to run, await new Promise((resolve) => setImmediate(resolve)) is the usual way to let all pending I/O callbacks and microtasks settle before the next assertion, and it is faster than a fixed sleep.

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.