Sobes.tech
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:

  1. The main thread executes synchronous code.
  2. Asynchronous operations (timers, network requests, events) are sent to Web APIs.
  3. When an asynchronous operation completes, its callback is placed in the task queue.
  4. The Event Loop constantly checks if the call stack is free.
  5. 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.