How Web APIs Handle Asynchronous Operations
Web APIs play a crucial role in enabling JavaScript to perform asynchronous tasks. They interact with the call stack and event loop to handle operations like timers, HTTP requests, and DOM events.
Step by step
Execution Flow:
- Call Stack: Logs 'Start' and 'End'.
- Web API: setTimeout sends the callback to the browser's Web API with a timer of 2 seconds.
- Callback Queue: After 2 seconds, the callback (console.log('Inside setTimeout')) moves to the callback queue.
- Event Loop: Pushes the callback to the call stack after the main thread finishes.
Output:
Start
End
Inside setTimeoutExamples
Understanding Web APIs and Event Loop:
console.log('Start');
setTimeout(() => {
console.log('Inside setTimeout');
}, 2000);
console.log('End');Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus