Schedule work on the microtask queue
Promise callbacks and setTimeout callbacks do not share a queue. Everything queued by a resolved promise runs as soon as the current synchronous code finishes, and only after that queue is empty does the engine reach for a timer callback. Batching libraries lean on this to collapse many updates into one.
Implement soon(fn). It schedules fn to be called on the microtask queue: after the currently running synchronous code, and before any setTimeout callback, even one that was scheduled earlier with a delay of 0. Callbacks scheduled with several soon calls run in the order they were scheduled, and a soon called from inside a scheduled callback still runs before any pending timer.
Arguments
fnFunction- The callback to schedule on the microtask queue.
Returns
void — Returns nothing. fn runs asynchronously, after the current synchronous code finishes.
Examples
const order = [];
soon(() => order.push("micro"));
order.push("sync");
// after this tick: order === ["sync", "micro"]The scheduled callback waits for the current synchronous code to finish.
const order = [];
setTimeout(() => order.push("timer"), 0);
soon(() => order.push("micro"));
// after a tick: order === ["micro", "timer"]Microtasks beat even a 0ms setTimeout.
What it has to do
- Never call
fnsynchronously. - Call
fnbefore any already-scheduledsetTimeoutcallback. - Run several scheduled callbacks in scheduling order.
- Do not use
setTimeoutto schedule the callback.
Notes
Promise.resolve().then(fn)andqueueMicrotask(fn)both work — the whole trick is picking the microtask queue over the timer queue.- Chained microtasks run to completion before any timer fires, which is why render-batching libraries flush this way.
Stuck? The javascript course covers everything this challenge needs.
- 1.runs after the current synchronous code
- 2.runs before a setTimeout scheduled earlier
- 3.keeps scheduling order
- 4.a nested schedule still beats a pending timer
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.