bhylu.com

Advertisements

Node.js Event Loop and Timers

Scheduling APIs run callbacks at different opportunities. Use them to express a needed relationship rather than guessing an ordering that Node does not guarantee in your context.

How it works

Promise handlers and queueMicrotask callbacks belong to microtask processing. Timers specify a minimum delay rather than a precise appointment. setImmediate and setTimeout ordering depends on where they are scheduled, and ESM evaluation has its own context for microtasks. This fixture checks only an explicit synchronous-to-microtask relationship and awaits a timer through its promise API. It does not assert an unstable nextTick-versus-promise or timer-versus-immediate ordering.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as scheduling.mjs in a separate empty exercises folder and run node scheduling.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

scheduling.mjs

import { setTimeout as delay } from 'node:timers/promises';
const order = ['script'];
queueMicrotask(() => order.push('microtask'));
await Promise.resolve();
console.log(order.join(' -> '));
await delay(1);
console.log('Timer completed');

Expected result

script -> microtask
Timer completed

The output establishes a relationship that the code deliberately creates. The one-millisecond value is not a latency promise, and a slow machine can complete the timer later without violating its contract. Measure real delays separately when they matter.

Use the Node.js API reference for the precise version contract.