🌐 What is the Event Loop?
The event loop is a critical component of JavaScript's runtime environment that enables asynchronous behaviour without blocking the main thread. It continuously checks the message queue for pending tasks and processes them one by one, ensuring that your application remains responsive.
🔄 Event Loop Phases
Call Stack:
The call stack is a data structure that records the execution context of functions. When a function is called, it's added to the top of the stack, and when it completes, it's removed from the stack.Web APIs:
Web APIs are provided by the browser or the environment in which JavaScript runs. They include features like setTimeout, setInterval, DOM events (click, scroll, etc.), fetch, and more.Message Queue:
The message queue holds tasks sent by the Web APIs. Each task consists of a callback function waiting to be executed.Event Loop:
The event loop continuously checks the call stack and the message queue. If the call stack is empty, it moves tasks from the message queue to the call stack for execution.
📷 Example
const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");
bar();
foo();
baz();
Credit: Lydia Hallie
Here is the js visual execution: view here
💡 Explanation
- First, the
bar()
function is called. This function contains setTimeout, which is an asynchronous function. It schedules the execution of its callback function (Second) after a delay of 500 milliseconds. The event loop adds this task to the message queue and moves on. - Next, the
foo()
function is called. It logs First to the console immediately and returns. - After that, the
baz()
function is called, which logs Third to the console immediately and returns. - Now, the call stack is empty, and the event loop starts processing the tasks in the message queue.
- The event loop picks the first task from the message queue, which is the callback function of setTimeout from the
bar()
function. The callback logs Second to the console.
📚 Homework
- what is the difference between task queue & micro task queue?
- Give me the example with micro & macro task queue.
Write the answers in the comment section
Top comments (0)