Middle
Tell us about the Event Loop in JavaScript/browser.
sobes.tech AI
Answer from AI
Event Loop is a mechanism in JavaScript and browsers that allows processing asynchronous operations without blocking the main thread.
JavaScript is single-threaded, but thanks to the Event Loop, it can perform tasks asynchronously:
- The main thread executes synchronous code.
- Asynchronous operations (timers, network requests, events) are sent to Web APIs.
- When an asynchronous operation completes, its callback is placed in the task queue.
- The Event Loop constantly checks if the call stack is free.
- If the stack is empty, the Event Loop takes the first callback from the task queue and places it on the stack for execution.
Thus, the Event Loop ensures non-blocking code execution, allowing the browser to remain responsive.
Example:
console.log('Start');
setTimeout(() => {
console.log('Timeout callback');
}, 0);
console.log('End');
The output will be:
Start
End
Timeout callback
Because the callback from setTimeout goes into the queue and executes after the synchronous code finishes.