Modern JavaScript from Scratch
98%
Section 5 · Lesson 6 of 6

Keeping the page responsive

Reading · 12 min Elena Marchetti

JavaScript runs one thing at a time. Yet a page can wait for a server, count down a timer and answer a click, all at once. The event loop is how: a queue of work the browser hands back to your code whenever it is free.

One thing at a time

Your code runs on a single call stack. A function is pushed on when it is called and popped off when it returns. While the stack is busy, nothing else of yours runs: not a click handler, not a timer.

console.log('one');
setTimeout(() => console.log('three'), 0);
console.log('two');

// one, two, three

Even with a delay of zero, three comes last. The timer's callback waits in a queue until the stack is empty.

The stack runs your code; finished timers and events wait in the queue for their turn.

Tasks and microtasks

There are two queues. Timers and events are tasks. Promise callbacks are microtasks, and every microtask runs before the next task does. That is why a resolved promise's then runs before a setTimeout of zero.

A long loop blocks everything: clicks, timers and screen updates all wait for it. Split heavy work into pieces, or move it off the page's thread.

Points to keep

  • Your code runs on one call stack, one function at a time.
  • Timers and events wait in a queue until the stack is empty.
  • Promise callbacks run before the next timer or event.
  • Keep long work short, or split it, so the page stays responsive.