The Event Loop, Visualized

One thing at a time โ€” interactive event loop example

1function makeCoffee() {
2 console.log('coffee ready');
3}
4
5console.log('open the shop');
6makeCoffee();
7console.log('close the shop');

The script runs top to bottom on the call stack. console.log("open the shop") executes and returns immediately.

1 / 7

Call stack

script

Web APIs โ€” browser land

The event loop โ€” is the call stack empty? โ†’ drain the microtask queue first โ†’ then take one callback.

Microtask queue โ€” priority

Callback queue

Console

01open the shop

Fig. โ€” One thing at a time ยท step 1 of 7

What is going on here

Before any of the async machinery makes sense, the call stack has to. JavaScript runs on a single thread with a single stack: calling a function pushes a frame on top, returning pops it off, and only the topmost frame is ever running.

That is why the output here is not the order the functions appear in the file. console.log("open the shop") runs, then makeCoffee is called and its frame goes on top, so "coffee ready" prints before control returns and "close the shop" runs. Nothing is queued and nothing waits โ€” every line finishes completely before the next one starts.

Hold on to the shape of this, because every asynchronous example is a departure from it. The event loop only gets a turn when this stack is empty, so the whole question "when does my callback run?" is really the question "when does the stack finally clear?".

Common questions

What is the call stack in JavaScript?

It is the structure that tracks which function is currently running. Each call pushes a frame, each return pops one, and because there is only one stack, only one piece of JavaScript can execute at a time.

Is JavaScript single-threaded?

Yes, your code runs on one thread with one call stack. Timers, network requests and other asynchronous work happen outside that thread, but their callbacks still have to queue up and run on it one at a time.

Does synchronous code ever involve the event loop?

Not while it is running. The event loop only gets a turn once the call stack is empty, so a purely synchronous script runs start to finish before the loop does anything at all.

Every question on one page โ†’ยทRun your own code โ†’

Embed this figure in your own post โ†’

Drop this into any article or course page. It stays interactive โ€” readers can step through it without leaving your site.