Wait for the next event loop
Resolve after the current task, letting queued timers, I/O and rendering run.
function nextTask() { return new Promise(resolve => setTimeout(resolve, 0)); }
Usage
const order = [];
const done = nextTask().then(() => order.push('timer'));
Promise.resolve().then(() => order.push('microtask'));
order.push('sync');
await done;
order; // → ['sync', 'microtask', 'timer']
Know the limits
- Promise callbacks (microtasks) still run before the timer, as the example shows.
- The HTML standard clamps timers nested more than five levels deep to at least 4 ms, so a chain of zero-delay timers is slower than it looks.
- In Node.js, setImmediate runs after pending I/O callbacks.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Wait for the next event loop from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.