Junior — Middle
Can you explain how the Event Loop works in JavaScript?
sobes.tech AI
Answer from AI
The Event Loop in JavaScript is a mechanism that allows asynchronous operations to be processed without blocking the main thread.
How it works:
- Function calls and synchronous code are executed immediately on the call stack.
- Asynchronous operations (e.g., timers, network requests) are sent to Web APIs (browser) or the corresponding API in Node.js.
- When an asynchronous operation completes, its callback is placed in the task queue.
- The Event Loop constantly checks the call stack: if it is empty, it takes the first callback from the task queue and places it on the stack for execution.
Thus, JavaScript remains single-threaded but can efficiently handle asynchronous operations without blocking.
Example:
console.log('Start');
setTimeout(() => {
console.log('Asynchronous call');
}, 0);
console.log('End');
// Output will be:
// Start
// End
// Asynchronous call