🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript The Event Loop

The event loop is the mechanism that runs JavaScript code in order. It moves work from the task queue onto the call stack when the stack is empty.

A timer runs last

The timer callback waits while the main script runs. The console shows the timer line after the other two lines.

console.log("First");
setTimeout(() => { console.log("Timer"); }, 0);
console.log("Last");

The call stack in action

Each function call goes on top of the stack. The function runs, then it leaves the stack.

function greet() { console.log("Inside greet"); }
console.log("Before call");
greet();
console.log("After call");

The queue keeps order

Two timers join the queue in order. The loop runs them in that same order.

setTimeout(() => { console.log("Timer one"); }, 0);
setTimeout(() => { console.log("Timer two"); }, 0);
console.log("Sync code");

Example

console.log("Start");
setTimeout(() => { console.log("Timer done"); }, 50);
console.log("End");

Key points

  • Call stack: the list of functions that are running right now
  • Task queue: the waiting line for work that is ready to run
  • The event loop moves one task from the queue onto the stack when the stack is empty.
  • JavaScript runs one thing at a time, so a slow task blocks the next one.
  • A timer callback waits in the queue until the stack clears.
  • The loop keeps running as long as there is work to do.

In this example, the first line prints Start. The timer line is set for 50 milliseconds, so it waits in the queue. The last line prints End before the timer line appears.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the event loop do?