Skip to content
BENIBIX Learn

Event Loop

Development🧭 Programming ParadigmsAsynchronous Code

Also known as JavaScript Event Loop, Run Loop

The loop that picks which waiting job runs next. It keeps one thread busy.

Think of it like

Think of it like a waiter with one pair of hands. The waiter serves one table, then checks who is ready.

Example

Jack logs 1, sets a 0 ms timer for 2, then logs 3. The page prints 1, 3, 2, because the timer waits for the queue.

Why it matters

It explains why a long loop freezes a page. It also shows why code may not run in the order written.

Definition

The event loop is the part of a runtime that decides what code runs next. JavaScript runs on one thread, so only one piece of code runs at a time. Slow tasks are handed off, and their callbacks wait in a queue. Each time the current code finishes, the loop takes the next waiting job. Promise jobs go before timer jobs, which is why a 0 ms timer still runs last.

Example code

javascript
console.log(1);
setTimeout(() => console.log(2), 0);
console.log(3);
// 1
// 3
// 2
The timer's job waits until the code in front has finished.

Common mistake

Running a heavy loop on the main thread. Nothing else, not even clicks, can run until it ends.

Key takeaways

  1. 1
    One thing at a time. On a single thread.
  2. 2
    A queue of jobs. Waiting their turn.
  3. 3
    Promises first. Then timers.