Hello ๐
Let's start with Event loop
One-Byte Explainer:
The Event Loop is like a traffic cop for JavaScript's code, managing a lane (callback queue) where tasks wait. The cop (Event Loop) processes tasks one by one, checking the call stack and ensuring everything runs smoothly.
Demystifying JS: Event Loop in Action
Event Loop manage asynchronous operations, allowing programs to continue running without getting stuck.
Let's look at a code example and its explanation:
console.log("data"); // Output: "data" (immediately)
for (let i = 0; i < 10; i++) {
console.log(i); // Output: 0, 1, 2, ..., 9 (immediately, one by one)
}
setTimeout(() => {
console.log('timer operations'); // Scheduled for later execution
}, 10); // Reliable delay of 10 milliseconds
console.log("after setTimeout"); // Placed after setTimeout for clarity
setTimeout is a function in JavaScript, but it is not a built-in function of the language itself. When you call setTimeout in your JavaScript code, the browser's JavaScript engine creates a timer in the Web API.
Here is the flow for better understanding:
"data" and the loop outputs from 0 to 9 are printed immediately.
Once the loop execution is done, the setTimeout callback is scheduled.
The timer starts as part of the Web API.
Meanwhile, the event loop keeps an eye on the callback queue for any results from asynchronous operations.
Synchronous operations continue, printing "after setTimeout".
After 10 milliseconds, the timer completes and the setTimeout callback is placed in the callback queue.
The event loop checks the call stack, and once it's empty, it pushes the first item in the queue to the stack for execution, printing "timer operations".
Thank you for reading , See you in the next blog