Interview question
What are Web APIs and how do they enable asynchronous behavior in JavaScript? Web APIs क्या हैं और JavaScript में asynchronous behavior कैसे enable करते हैं?
Answer
Web APIs (like setTimeout, fetch, DOM events) are provided by the browser (or Node.js runtime), not the JavaScript engine itself. They let time-consuming operations run outside the single call stack, without blocking execution.
console.log('1: Start');
// setTimeout is a Web API, NOT part of core JavaScript
setTimeout(() => {
console.log('3: Timeout callback');
}, 2000);
console.log('2: End');
// Output order: 1: Start, 2: End, 3: Timeout callback (after 2s)
// The setTimeout call itself returns immediately - the TIMER runs in the
// browser's Web API environment, separate from the JS call stack
// How it works step by step:
// 1. setTimeout() is called, JS hands off the timer + callback to the Web API
// 2. JS immediately continues executing the NEXT line (console.log('2: End'))
// 3. The Web API environment counts down the 2000ms independently
// 4. When the timer expires, the callback is placed in the CALLBACK QUEUE
// 5. The event loop moves it to the call stack ONLY when the stack is empty
// Common Web APIs that enable async behavior:
// - setTimeout / setInterval (timers)
// - fetch (network requests)
// - addEventListener (DOM events)
// - XMLHttpRequest
// - Geolocation, requestAnimationFrame, etc.
// Fetch example - the actual network request happens outside the call stack
console.log('Fetching...');
fetch('/api/data')
.then(response => response.json())
.then(data => console.log('Data received:', data));
console.log('This logs before fetch resolves');
// The browser's networking stack handles the request in the backgroundWeb APIs (setTimeout, fetch, DOM events जैसे) browser (या Node.js runtime) provide करता है, JavaScript engine खुद नहीं। यह time-consuming operations को single call stack के बाहर बिना block किए चलने देते हैं।
console.log('1: Start');
// setTimeout एक Web API है, core JavaScript का हिस्सा नहीं
setTimeout(() => {
console.log('3: Timeout callback');
}, 2000);
console.log('2: End');
// Output order: 1: Start, 2: End, 3: Timeout callback (2s बाद)
// setTimeout call तुरंत return करता है - TIMER browser के Web API में चलता है
// कैसे काम करता है step by step:
// 1. setTimeout() call होता है, JS timer+callback को Web API को दे देता है
// 2. JS तुरंत अगली line चलाता रहता है
// 3. Web API environment 2000ms independently count करता है
// 4. Timer खत्म होने पर callback CALLBACK QUEUE में जाता है
// 5. Event loop इसे stack खाली होने पर ही call stack में लाता है
// Async behavior enable करने वाले common Web APIs:
// - setTimeout / setInterval
// - fetch
// - addEventListener
// - XMLHttpRequest
// Fetch example
console.log('Fetching...');
fetch('/api/data')
.then(response => response.json())
.then(data => console.log('Data received:', data));
console.log('यह fetch resolve होने से पहले चलता है');Was this answer clear?