careerbydoing
← Web development

Web development

What runs when

About 5 min if you have seen this material before, 20 min or so if it is new to you.

Background
JavaScript runs on a single thread, so it must never block: instead of waiting for a timer or a network reply, it registers a callback and moves on. The The scheduler that runs JavaScript's synchronous code to completion first, then queued asynchronous callbacks. decides when those callbacks actually run, and the rule is strict: all synchronous code runs to completion first, before any callback at all. Once the synchronous code is done, two queues are drained in order. A promise is a value that is not ready yet; await pauses a function until it is. callbacks sit on the microtask queue, which is emptied first and completely. Timer callbacks from setTimeout sit on the macrotask queue, which is only reached afterwards. This is why setTimeout(fn, 0) does not mean "run now". It means "run after everything currently pending", which is a considerably weaker promise.
In what order do the four letters appear? Answer as four letters, e.g. ABCD.
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");

Past 45 min on this? That usually means a missing prerequisite rather than a lack of effort — worth reading up before pushing further, starting with JavaScript execution model (MDN).

Want to go deeper?