Skip to content

Instantly share code, notes, and snippets.

@jesstelford
Last active August 27, 2024 02:04
Show Gist options
  • Save jesstelford/9a35d20a2aa044df8bf241e00d7bc2d0 to your computer and use it in GitHub Desktop.
Save jesstelford/9a35d20a2aa044df8bf241e00d7bc2d0 to your computer and use it in GitHub Desktop.
What is the JS Event Loop and Call Stack?

Regular Event Loop

This shows the execution order given JavaScript's Call Stack, Event Loop, and any asynchronous APIs provided in the JS execution environment (in this example; Web APIs in a Browser environment)


Given the code

setTimeout(() => { 
  console.log('hi')
}, 1000)           

The Call Stack, Event Loop, and Web APIs have the following relationship

        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   |              | |               |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

To start, everything is empty


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          |              | |               |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

It starts executing the code, and pushes that fact onto the Call Stack (here named <global>)


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
> setTimeout(() => {  | <global>          |              | |               |
    console.log('hi') | setTimeout        |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

Then the first line is executed. This pushes the function execution as the second item onto the call stack.

Note that the Call Stack is a stack; The last item pushed on is the first item popped off. Aka: Last In, First Out. (think; a stack of dishes)


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
> setTimeout(() => {  | <global>          |              | | timeout, 1000 |
    console.log('hi') | setTimeout        |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

Executing setTimeout actually calls out to code that is not part of JS. It's part of a Web API which the browser provides for us. There are a different set of APIs like this available in node.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          |              | | timeout, 1000 |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

setTimeout is then finished executing; it has offloaded its work to the Web API which will wait for the requested amount of time (1000ms).


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   |              | | timeout, 1000 |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

As there are no more lines of JS to execute, the Call Stack is now empty.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   | function   <-----timeout, 1000 |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

Once the timeout has expired, the Web API lets JS know by adding code to the Event Loop.

It doesn't push onto the Call Stack directly as that could intefere with already executing code, and you'd end up in weird situations.

The Event Loop is a Queue. The first item pushed on is the first item popped off. Aka: First In, First Out. (think; a queue for a movie)


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function        <---function     | |               |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

Whenever the Call Stack is empty, the JS execution environment occasionally checks to see if anything is Queued in the Event Loop. If it is, the first item is moved to the Call Stack for execution.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function          |              | |               |
>   console.log('hi') | console.log       |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |

Executing the function results in console.log being called, also pushed onto the Call Stack.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function          |              | |               |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |
> hi

Once finished executing, hi is printed, and console.log is removed from the Call Stack.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   |              | |               |
    console.log('hi') |                   |              | |               |
  }, 1000)            |                   |              | |               |
                      |                   |              | |               |
> hi

Finally, the function has no other commands to execute, so it too is taken off the Call Stack.

Our program has now finished execution.

End.

Starved Event Loop

Below is an example of how code running in the current Call Stack can prevent code on the Event Loop from being executed. aka; the Event Loop is starved.


Given the code

setTimeout(() => { 
  console.log('bye')
}, 2)           
someSlowFn()
console.log('hi')
        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   |              | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

To start, everything is empty


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          |              | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

It starts executing the code, and pushes that fact onto the Call Stack (here named <global>)


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
> setTimeout(() => {  | <global>          |              | |               |
    console.log('bye')| setTimeout        |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

setTimeout is pushed onto the Call Stack


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
> setTimeout(() => {  | <global>          |              | | timeout, 2    |
    console.log('bye')| setTimeout        |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

setTimeout triggers the timeout Web API


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          |              | | timeout, 2    |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

setTimeout is then finished executing, while the Web API waits for the requested amount of time (2ms).


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          |              | | timeout, 2    |
    console.log('bye')| someSlowFn        |              | |               |
  }, 2)               |                   |              | |               |
> someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

someSlowFn starts executing. Let's pretend this takes around 300ms to complete. For that 300ms, JS can't remove it from the Call Stack


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          | function   <-----timeout, 2    |
    console.log('bye')| someSlowFn        |              | |               |
  }, 2)               |                   |              | |               |
> someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

Meanwhile, the timeout has expired, so the Web API lets JS know by adding code to the Event Loop.

someSlowFn is still executing on the Call Stack, and cannot be interrupted, so the code to be executed by the timeout waits on the Event Loop for its turn.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          | function     | |               |
    console.log('bye')| someSlowFn        |              | |               |
  }, 2)               |                   |              | |               |
> someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

Still waiting for someSlowFn to finish...


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          | function     | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
> someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

someSlowFn finally finished!


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          | function     | |               |
    console.log('bye')| console.log       |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
> console.log('hi')   |                   |              | |               |

The next line is executed, pushing console.log onto the Call Stack


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | <global>          | function     | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
> console.log('hi')   |                   |              | |               |

> hi

We see hi output on the console thanks to console.log


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   | function     | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

> hi

Nothing left to execute, so the special <global> is popped off the Call Stack.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function        <---function     | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

> hi

This frees up the JS execution environment to check the Event Loop for any code which needs to be executed.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function          |              | |               |
>   console.log('bye')| console.log       |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

> hi

Executing the function results in console.log being called, also pushed onto the Call Stack.


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  | function          |              | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

> hi
> bye

Once finished executing, bye is printed, and console.log is removed from the Call Stack.

Notice that by this point, it is at least 300ms after the code originally requested the setTimeout. Meaning even though we asked for it to be executed after only 2ms, we still had to wait for the Call Stack to empty before the setTimeout code on the Event Loop could be executed

Note: Even if we didn't have someSlowFn, setTimeout is clamped to 4ms as the mimimum delay allowed in some cases


        [code]        |   [call stack]    | [Event Loop] | |   [Web APIs]  |
  --------------------|-------------------|--------------| |---------------|
  setTimeout(() => {  |                   |              | |               |
    console.log('bye')|                   |              | |               |
  }, 2)               |                   |              | |               |
  someSlowFn()        |                   |              | |               |
  console.log('hi')   |                   |              | |               |

> hi
> bye

Finally, there are no other commands to execute, so it too is taken off the Call Stack.

Our program has now finished execution.

End.

Note: It's also possible to starve the event loop with Promises via the "Microtask queue"

@kevinjie
Copy link

nice explanation, it is very useful, thanks

@ekaterina-lepunova
Copy link

cool, thanks :)

@superhuman54
Copy link

nice :)

@AndrewSavetchuk
Copy link

Love these visual explanations, thanks!

@Majd-eddine-BEN-TAHAR
Copy link

nice nice nice yes yes yes ha ha ha! cool Thank You

@lofayo
Copy link

lofayo commented Dec 19, 2019

thanks , the article is easier than i haved readed others to understand

@ananda4809
Copy link

nice article. easier to understand.

@abkisssb
Copy link

abkisssb commented Jun 3, 2020

Thanks, its a super cool article

@shauryaprataap
Copy link

Nicely Explained.

@tomarpremveer
Copy link

One of the finest explanation of the topic.
thank you sir

@ivanlynch
Copy link

Thanks, really nice article!

@deepaksinghmudila
Copy link

Amazing explanation man.

@afandimsr
Copy link

Thanks, nice article

@wenxiayili
Copy link

wenxiayili commented Jun 1, 2021

Thanks, the simple and clear explanation.

@Deep-Codes
Copy link

Fantastic Thanks a ton 🚀

@pmrubenrao
Copy link

Thats great explaination

@znamazbayeva
Copy link

thank you!

@juan94v
Copy link

juan94v commented Mar 18, 2022

Thank you!

@Rootjang92
Copy link

That's great! thanks.

@mak0Legion
Copy link

that is just amazing ! thanks a lot mate

@Satyendra07
Copy link

Thanks for this article

@felipetaborvillegas
Copy link

Thanks!!! great article

@Harry-Kwesi
Copy link

This is great. thanks

Copy link

ghost commented Apr 6, 2023

thanks bro : )

@debasishmohanty
Copy link

Very well explained... Thank you so much!!

@Carl0sCastellanos
Copy link

Excelente explicación. Gracias

@gorkemozkan
Copy link

thank you!

@waiyanhtun282
Copy link

thank you

@sidanand67
Copy link

best explanation

@suraj-sella
Copy link

Amazing explanation this one. Thanks for making this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment