Middle
Tell me about the event loop: what is it for, how does it work?
sobes.tech AI
Answer from AI
Event loop — this is a mechanism in JavaScript that allows executing asynchronous code without blocking the main thread.
Purpose: JavaScript is single-threaded, but it often needs to perform time-consuming operations (e.g., server requests, timers). The event loop allows such tasks to be queued and executed when ready, ensuring application responsiveness.
How it works:
- There is a call stack where the current code is executed.
- There is a task queue where callbacks of asynchronous operations are placed.
- The event loop constantly checks if the call stack is empty.
- If the stack is empty, the event loop takes the first task from the queue and pushes it onto the stack for execution.
This allows, for example, timers to run or events to be processed without blocking the main thread.
Example:
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
The output will be:
Start
End
Timeout
Because the setTimeout callback goes into the task queue and executes after the main code finishes.