Once upon a time there was a hotel where there was only one waiter and five tables. Role of waiter was as usual. Take orders from the table, provide orders to cook and once orders are ready, serve it to tables.
The job of the waiter is to keep serving the tables and his job is not finished until all tables are served. His work is like a loop.
- Take the order from a table, say
- Notice any calls from other tables, say
- Provide order of
Table 1to cook.
- Till order is ready, take order from
Table 2and provide that order to cook
- Once any order is ready, the cook will notify the waiter.
- Once the waiter’s task in hand is done, the waiter will serve the order to the corresponding table.
- Call Stack (Task in hand)
- Event Queue (Pending task list)
Call Stack. Every statement will be executed using the call stack in LIFO order. If a statement has to be executed at a later point in time, that statement gets moved to the event queue. Once that later point comes, that statement gets moved back to the call stack.
All pending tasks are kept in this queue. It works in FIFO order. All statements of the event queue are supposed to move to the Call stack for the execution.
Classic Example of Event Loop
It has two parts
- callback function
- timeout in milliseconds
setTimeout statement is executed, it’s callback is kept in the event queue. Once it’s timeout is complete, that callback is moved to the call stack for execution.
Whenever there is any async request like setTimeout, callback code is added in the event queue.