Event Loop in JavaScript

Event Loop by Yuvraj Patil

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.

  1. Take the order from a table, say Table 1.
  2. Notice any calls from other tables, say Table 2.
  3. Provide order of Table 1 to cook.
  4. Till order is ready, take order from Table 2 and provide that order to cook
  5. Once any order is ready, the cook will notify the waiter.
  6. Once the waiter’s task in hand is done, the waiter will serve the order to the corresponding table.

Event loop is a core concept of JavaScript. As the name suggests, it’s a loop that means something is happening repetitively. So here, what is happening repetitively is an event.

Event loop is a concept which involves following JavaScript core concepts:

  • Call Stack (Task in hand)
  • Event Queue (Pending task list)

All JavaScript statements are executed inside the Call Stack one by one. If a statement has to be executed at a later point in time, it is moved to the event queue.

Call Stack

JavaScript is a single threaded language. All JavaScript statements are executed one by one using a stack called 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.

Event Queue

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

Whenever the 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.


Event Loop is part of the foundation of JavaScript. We have used it many times but we should know how it’s working behind the scenes.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yuvraj Patil

Yuvraj Patil

Loves coding and enjoys learning new technologies. Website: https://.yuvrajpatil.com