The event loop
Here's a simplified explanation of how the event loop works:
1. Call Stack:
2. Task Queue:
3. Event Loop:
The event loop continuously checks the call stack and the task queue. If the call stack is empty, it takes the first task from the task queue and pushes it onto the call stack to be executed.
4. Non-Blocking Operations:
When a non-blocking operation, such as an asynchronous network request or a setTimeout callback, is encountered, it is offloaded to the browser or the host environment. The event loop doesn't wait for the operation to complete; instead, it registers a callback for when the operation is finished.
5. Callback Execution:
Once the non-blocking operation is complete, the callback associated with it is added to the task queue.
6. Execution Order:
As the event loop iterates, it checks the call stack. If the stack is empty, it takes the next task from the task queue and pushes it onto the call stack, starting the execution of the associated callback.
// Asynchronous task 1
console.log("Async Task 1");
// Asynchronous task 2
console.log("Async Task 2");
In this example, we have three console.log statements and two setTimeout functions. The setTimeout functions simulate asynchronous tasks that will be executed after a specified delay.
When this code is executed, the output will be as follows:
Explanation of the event loop execution:
Async Task 2
Async Task 1
The first console.log("Start") statement is executed synchronously, and it logs "Start" to the console.
The first setTimeout function is encountered, which schedules the execution of its callback function after a 2-second delay. However, it doesn't block the execution, and the event loop continues.
The second setTimeout function is encountered, which schedules the execution of its callback function after a 1-second delay. Like the previous setTimeout, it doesn't block the execution.
The console.log("End") statement is executed synchronously and logs "End" to the console.
After the initial synchronous execution, the event loop continuously checks for tasks in the event queue.
After 1 second, the first setTimeout callback function is added to the event queue.
After 2 seconds, the second setTimeout callback function is added to the event queue.
The event loop picks the first task from the event queue, which is the callback function of the second setTimeout. It executes the function, logging "Async Task 2" to the console.
After completing the execution of the second setTimeout callback, the event loop picks the next task from the event queue, which is the callback function of the first setTimeout. It executes the function, logging "Async Task 1" to the console.
By following this process, the event loop
For best video explanation, check this