what is Event loop ?:
event loop:The event loop is a crucial concept in JavaScript's concurrency model. It manages the execution of multiple tasks, ensuring non-blocking behavior by continuously checking the call stack for tasks to execute, while also handling asynchronous operations such as callbacks, timers, and promises. This loop enables JavaScript to handle I/O operations efficiently and maintain responsiveness in web applications.
console.log('hi'); // Logs 'Start' synchronously
setTimeout(() => {
console.log('Timeout completed'); // Logs 'Timeout completed' asynchronously
}, 5000); // Set timeout for 2 seconds
console.log('End'); // Logs 'End' synchronously
Explanation:
console.log prints the "hi" in synchronously
setTimeout ():It sets a task asynchronously after delay of 5 seconds , it is written in program as milliseconds.
The provided arrow function will be added to the task queue once the timer expires.
then finally console.log prints "end " synchronously
call stack:
Entering Functions: Whenever a function is called, a "frame" representing that function's context is added to the top of the call stack.
Exiting Functions: When a function finishes executing, its frame is removed from the top of the call stack, allowing the program to return to the previous function or continue execution.
Callback Queue:
Asynchronous operations, like I/O tasks or timers, are initiated and managed by the browser or Node.js runtime environment.
Upon completion of these operations, their associated callback functions are queued in the callback queue, awaiting execution in a non-blocking manner.
event loop:
The event loop continually monitors both the call stack, which keeps track of function calls being executed, and the callback queue, where completed asynchronous operations' callbacks are stored.
When the call stack is empty, the event loop retrieves the first function/callback from the callback queue and pushes it onto the call stack, initiating its execution. This process ensures that asynchronous operations' callbacks are executed in the order they were received, maintaining the asynchronous and non-blocking behavior of the program.
execution:
The function currently atop the call stack is executed, and if it includes asynchronous code, it may trigger additional asynchronous operations.
These new asynchronous tasks are delegated to the runtime environment, allowing the main thread to continue executing without waiting for their completion, ensuring non-blocking behavior.
Callback Execution:
- When an asynchronous operation is complete, its callback is placed in the callback queue.
Repeat:
- The event loop continues this process, ensuring that the call stack is always empty before taking the next function from the callback queue.