Web APIs - How Async JavaScript Works Call Stack & Event Loop
Web APIs are not a feature of JavaScript itself.
They are provided by the browser (like Chrome, Firefox, Safari, etc.).
These APIs help JavaScript perform tasks that are not part of its core capabilities, such as:
- Timers (
setTimeout,setInterval) - Fetching data (
fetch, AJAX) - DOM events (click, scroll, etc.)
- Geolocation
- Console operations
Why do we need Web APIs?
JavaScript is a single-threaded language, which means:
- It can execute only one task at a time
Now imagine this:
- You make an API call that takes 10 seconds
- If JavaScript handled it directly, everything would freeze for 10 seconds
That would make your UI unresponsive.
Solution:
To avoid this, asynchronous tasks are handled outside the call stack, using Web APIs.
How Web APIs Work (Step-by-Step Flow)
Let’s simplify the flow:
1. Call Stack
- Handles all synchronous code
- Executes functions one by one
2. Web APIs
- When async operations appear (like
setTimeout), they are sent here - The browser handles them in the background
3. Callback Queue
- Once the async task is done, its callback is placed in the queue
4. Event Loop
- Continuously checks:
- Is the call stack empty?
- If yes → moves callback from queue to stack
Example
console.log("Start");
setTimeout(() => {
console.log("Inside Timeout");
}, 2000);
console.log("End");
Output:
Start
End
Inside Timeout
Explanation:
"Start"→ goes to call stack → executessetTimeout→ goes to Web API"End"→ executes immediately- After 2 seconds → callback goes to queue
- Event loop pushes it to stack → executes
Important Points
- Call Stack handles synchronous code
- Web APIs handle asynchronous operations
- Callback Queue stores completed async callbacks
- Event Loop manages execution flow
- This system ensures your app does not freeze
What about Node.js?
Good question.
Even though Node.js does not run in a browser:
- It uses the V8 engine (same as Chrome)
- Provides similar async APIs using its own system (like
libuv)
So, Web API-like behavior is still available in Node.js.
Interview Questions You Might Get
- What are Web APIs in JavaScript?
- Are Web APIs part of JavaScript?
- What is the role of the Event Loop?
- Difference between Call Stack and Callback Queue?
- How does JavaScript handle async operations?