Concurrency and External APIs
We know that JavaScript is single-threaded, non-blocking, and uses the Event Loop to manage background tasks. But this raises a major technical question:
If JavaScript only has one thread, who exactly is counting the 1000 milliseconds for setTimeout? Who exactly is actively managing the network socket for a fetch request while the main thread moves on?
The Secret: External APIs
The answer is External APIs provided by the host environment.
Functions like setTimeout, fetch, and document event listeners are not part of the core JavaScript language specifications (like V8 Engine). They are external Web APIs provided by the browser (or standard libraries provided by Node.js, Deno, or Bun).
How True Concurrency Works
While your JavaScript code and the V8 Engine are strictly single-threaded, the browser itself is written in C++ and is heavily multi-threaded!
Here is the full lifecycle of an asynchronous operation:
- Call: Your single-threaded JS code calls
setTimeout(callback, 1000). - Handoff: The JS Engine instantly hands that request off to the Browser’s external Timer API and moves on to the next line of code.
- Background Work: The Browser spins up a background C++ thread to actually sit there and count exactly 1000 milliseconds. True concurrency!
- Queue: Once the C++ timer finishes, the Browser takes the callback function and pushes it into the JavaScript Task Queue.
- Execution: When the Call Stack is empty, the Event Loop pulls the callback out of the Task Queue and executes it back on the single JS thread.