Middle+
What is an event loop?
sobes.tech AI
Answer from AI
The event loop is a mechanism that allows JavaScript to perform non-blocking operations despite its single-threaded nature.
How it works:
- The event loop constantly checks the callback queue.
- When the call stack is empty, the event loop takes the first event from the queue and pushes it onto the stack for execution.
This enables asynchronous operations (such as timers, network requests) to be processed without blocking the main thread.
Example:
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
console.log('End');
// Output will be:
// Start
// End
// Timeout
Here, the callback from setTimeout goes into the queue and executes after the main code has finished.