The event loop
Why code runs in the order it does, and why a long task freezes the page.
JavaScript has one call stack. Functions run to completion, one at a time. Asynchronous work (timers, network, events) is handled by the environment, and its callbacks are queued until the stack is empty. The event loop moves them from the queues onto the stack.
There are two important queues. Microtasks (promise callbacks, queueMicrotask) run before the next macrotask (setTimeout, DOM events, I/O).
console.log("1 start");
setTimeout(() => console.log("4 timeout"), 0);
Promise.resolve().then(() => console.log("3 promise"));
console.log("2 end");
// Output: 1 start, 2 end, 3 promise, 4 timeoutEven with a delay of 0, the timeout runs after the current code and after all pending microtasks.
Blocking the loop
button.onclick = () => {
for (let i = 0; i < 1e10; i++) {} // the page cannot repaint or respond meanwhile
};- Long synchronous work freezes the UI, because rendering also needs the main thread.
- Split work into chunks and yield between them (
await new Promise(r => setTimeout(r)), orscheduler.yield()where available). - Move heavy computation to a Web Worker, which runs in its own thread.
- Use
requestAnimationFramefor visual updates, so they happen just before a repaint.
NoteNode.js has the same model with extra phases (timers, I/O, setImmediate, process.nextTick). The ordering rules differ in details, so check the docs when order matters.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.