AniUI Academy

Schedule work on the microtask queue

easyAsync & Promises+150 XPPractice

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 fn synchronously.
  • Call fn before any already-scheduled setTimeout callback.
  • Run several scheduled callbacks in scheduling order.
  • Do not use setTimeout to schedule the callback.

Notes

  • Promise.resolve().then(fn) and queueMicrotask(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.

Try it yourself
Loading playground...
4 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.