setTimeout, setInterval, setImmediate, their clear* counterparts, and queueMicrotask are globals that follow
the HTML timer API.
Example
js
// htmltimers.mjs
setTimeout(() => {
const order = [];
setTimeout(() => order.push("timeout"), 0);
setImmediate(() => order.push("immediate"));
Promise.resolve().then(() => order.push("promise"));
queueMicrotask(() => order.push("microtask"));
process.nextTick(() => order.push("nextTick"));
setTimeout(() => console.log(order.join(" ")), 20);
}, 0);
let runs = 0;
const interval = setInterval(() => {
if (++runs === 2) {
clearInterval(interval);
console.log("interval ran", runs, "times; hasRef:", interval.hasRef());
}
}, 5);
utf-8 · js · Lines: 18
elide run htmltimers.mjs prints:
text
interval ran 2 times; hasRef: true
nextTick promise microtask immediate timeout
utf-8 · text · Lines: 2
Differences from browsers
- Timers return Node
TimeoutorImmediateobjects, not numbers, withref(),unref(),hasRef(), andrefresh()(Timeoutonly). - String handlers are not supported; the callback must be callable.
setTimeout(callback)without a delay printsTimeoutNaNWarningbefore running the callback; pass0.- At a checkpoint, callbacks run in this order:
process.nextTick- Promise and
queueMicrotaskcallbacks, in enqueue order setImmediate- Zero-delay timers
Reference
Status: Full · Not measured