Middle
What can you tell about asynchrony in the browser and the Event Loop? What does it consist of?
sobes.tech AI
Answer from AI
Asynchronous operations in the browser allow executing tasks without blocking the main thread, ensuring a smooth user interface.
Event Loop is a mechanism that manages the execution of code, event handling, and asynchronous tasks in JavaScript.
It consists of several parts:
- Call Stack — where the current code is executed.
- Callback Queue — stores functions ready to execute after asynchronous operations complete.
- Microtask Queue — contains higher-priority tasks, such as promises.
Working principle:
- Synchronous code from the call stack is executed.
- When the stack is empty, the Event Loop checks the microtask queue and executes all tasks there.
- Then, the Event Loop takes one task from the callback queue and places it on the stack for execution.
- The cycle repeats.
Example:
console.log('Start');
setTimeout(() => console.log('Timeout'), 0);
Promise.resolve().then(() => console.log('Promise'));
console.log('End');
The output will be:
Start
End
Promise
Timeout
Because microtasks (promises) are executed before callback queue tasks (setTimeout).
Thus, the Event Loop ensures asynchronous code execution, allowing the browser to remain responsive.