Skip to content

Event Loops

JavaScript runs one piece of code at a time, on a single thread. The event loop is the mechanism that lets it still respond to timers, network replies and clicks: when the code that is running finishes, the event loop picks the next waiting job and runs it, and it repeats this for as long as the program lives.

Knowing how the loop works explains why a setTimeout() of zero milliseconds does not run straight away, why promise callbacks run before timers, and why a long calculation freezes a page.

The call stack holds the functions that are running now. When a function calls another, the new one goes on top of the stack, and when it returns it comes off again. The stack empties when the current script has finished.

Work that has to wait, such as a timer or a network request, is handed to the environment, which is the browser or Node.js. When the timer expires or the reply arrives, the environment puts the callback in the task queue. The event loop takes a callback from that queue only when the call stack is empty.

console.log('1. Order received');
setTimeout(() => console.log('4. Courier collects the parcel'), 0);
console.log('2. Order packed');
console.log('3. Label printed');

This prints:

1. Order received
2. Order packed
3. Label printed
4. Courier collects the parcel

The delay is zero, but the callback still waits in the queue until the rest of the script has finished, so a delay is a minimum and not a guarantee of when the callback runs. Synchronous vs Asynchronous and Timers cover the same idea from the code’s side.

Promise callbacks, the code after an await, and functions passed to queueMicrotask() go in a separate, higher-priority microtask queue. Each time the call stack empties, the event loop runs every microtask, including any that are added while it does so, before it takes the next task.

console.log('script start');
setTimeout(() => console.log('timeout'), 0);
Promise.resolve().then(() => console.log('promise 1'));
queueMicrotask(() => console.log('microtask'));
Promise.resolve().then(() => console.log('promise 2'));
console.log('script end');

This prints:

script start
script end
promise 1
microtask
promise 2
timeout

The synchronous lines run first, because the script is itself a task. The three microtasks then run in the order they were queued, and the timer’s callback, which is a task, runs last.

Because the loop drains the whole microtask queue before moving on, a microtask that keeps queueing another one starves everything else, and timers, clicks and rendering then all wait.

While a function is running, nothing else can run. A timer that is due, a click and the next screen update all wait until the stack is empty.

const start = Date.now();
setTimeout(() => {
console.log(`Timer ran after ${Date.now() - start} ms`);
}, 10);
// Keep the call stack busy for about 200 ms
while (Date.now() - start < 200) {}
console.log('Loop finished');

This prints:

Loop finished
Timer ran after 204 ms

The exact figure varies from run to run, but it is always at least 200 milliseconds, although the timer asked for 10. In a browser, the page cannot repaint or respond to the user during that time either. Long calculations belong in a Web Worker, which runs on its own thread, or should be split into small pieces that each give the loop a turn.

In a browser, the event loop also decides when the page is redrawn. Between tasks, usually about 60 times a second, the browser can run requestAnimationFrame() callbacks, work out the layout and paint the screen. A change to the page made in a script therefore appears only after the script finishes, and an animation driven by requestAnimationFrame() stays in step with the screen.

The MDN page on the JavaScript execution model and the HTML standard’s section on event loops go into more detail.

Philip Roberts covers this topic in his JSConf EU talk What the heck is the event loop anyway?.