Scheduling Node.js tasks with nextTick, setImmediate, and setTimeout

Determine task order under explicit runtime conditions and avoid relying on unstable timing.

🎯 Introduction

By the end of this article, you will be able to determine task order under explicit runtime conditions and avoid relying on unstable timing.


🧱 Establish the runtime conditions first

All examples here use ESM (.mjs) in Node.js 24.19.0. Save and run each example independently. When reasoning about order, note whether tasks are registered at module top level or inside an I/O callback.

setTimeout runs after its waiting threshold is reached. setImmediate runs in the check phase. process.nextTick adds work to a dedicated queue processed with priority after the current operation.


⏱️ nextTick: run after the current code

Save this as tick.mjs and run node tick.mjs:

tick.mjs
process.nextTick(() => console.log('nextTick'))
console.log('Synchronous code')

This prints Synchronous code, then nextTick. It defers work until after the current synchronous operation, generally before the event loop advances through regular phases.

Do not keep adding tasks recursively to this queue. If it never drains, file, network, and other I/O may be delayed for a long time.


⚖️ ESM top level: Promise callbacks precede nextTick

This example runs at the top level of an ESM file: directly in the file, outside other callbacks. Save it as microtasks.mjs:

microtasks.mjs
Promise.resolve().then(() => console.log('Promise'))
process.nextTick(() => console.log('nextTick'))

Run node microtasks.mjs. It prints Promise before nextTick. ESM top-level code executes as part of asynchronous module loading, so the Promise callback registered here is processed first.

If another resource says “nextTick precedes Promise,” check its environment. These same lines at CJS top level print nextTick first; at the ESM top level used in this course, Promise comes first. Different module execution models explain the difference.

This conclusion applies only to the top-level example, not directly to code inside callbacks such as file read handlers.


🕒 timeout and immediate: no guaranteed top-level order

Save this as timers.mjs:

timers.mjs
setTimeout(() => console.log('timeout'), 0)
setImmediate(() => console.log('immediate'))

You may see timeout first or immediate first. Even 0 requires the timer to meet its execution conditions, and actual timing when entering the event loop affects the result. Repeatedly observing the same order does not establish a reliable guarantee.

Despite its name, setImmediate waits for the check phase. It does not interrupt running code either.


📂 Order inside I/O callbacks depends on a specific condition

The previous event loop article demonstrated that setImmediate precedes setTimeout when both are registered in the same file read callback. The registration location differs from the top-level example here. Do not memorize a fixed order without this condition.


🧰 Await actual application dependencies

For everyday file and network tasks, wait directly for the corresponding API result. You do not need another scheduling function just to make work asynchronous.

GoalApproach
Use contents after reading finishesAwait the readFile Promise or handle the completion callback
Retry after a delayUse setTimeout; the delay is a minimum wait, not an exact execution time
Split computation into batches so I/O can runSchedule the next batch with setImmediate after each batch; each batch must still remain short

Comparing nextTick order helps you understand existing code. It should not be the default asynchronous entry point for application logic. Its queue drains with priority, so repeated scheduling can postpone I/O.

When reading after writing, await write completion before starting the read. Do not use setTimeout(..., 0) to guess that writing has finished. Neither nextTick nor setImmediate proves that another I/O operation has completed.


❓ Questions and answers

Q1: Does nextTick always precede Promise?

No. Promise callbacks run first in this ESM top-level example. Check where tasks are registered.

Q2: Why does I/O callback ordering not apply directly to top-level code?

An I/O callback has a specific position relative to subsequent phases. Top-level registration also depends on timing when entering the loop, so the conditions differ.

Q3: Does recursively scheduling nextTick improve throughput?

It may instead prevent the event loop from advancing and leave I/O waiting for a long time.


🧪 Exercise

Swap the two lines in microtasks.mjs, rerun it, and record the result. Check whether registration order determines execution order in this example.

// Write your code here

🎉 Try these techniques with your own examples!