DEV Community

Cover image for  ✨♻️ JavaScript Visualized: Event Loop

✨♻️ JavaScript Visualized: Event Loop

Lydia Hallie on November 20, 2019

Oh boi the event loop. It’s one of those things that every JavaScript developer has to deal with in one way or another, but it can be a bit confusi...
logan70 profile image

Hi, Lydia Hallie, it is a great article.

Can I translate this article into Chinese to help more Chinese developers(With original author and link, of course).

lydiahallie profile image
Lydia Hallie Author


karataev profile image
Eugene Karataev

Thanks for the great article and animations!
It's interesting why "event loop" question is so common on interviews, if it's job is just to transport code blocks from the queue to the call stack. I think better question would be to ask to describe how the JS mechanism works as a whole thing with call stack, web api, queue and event loop.

diegolepore profile image
Diego Palacios Lepore

Hi, Lydia!

This is such a great article! 😃

I was looking a clear post about this subject and yours is super comprehensive and well explained (btw, I loved the gifs). I'm planning to talk to my team about the event loop soon (in spanish).

I'm sure you might have heard about this tool that helps you play with this cycle and see in real time how it goes:

rafaelbeckel profile image
Rafael Beckel

Interesting article! What did you use to animate the gifs?

lydiahallie profile image
Lydia Hallie Author

As a true professional I use keynote and screen record it lol

igmuska profile image

total de minimis production effect, the simplest way is usually the correct, least expensive way, Occam's Razor

squidbe profile image

Professional enough!

thebilson profile image

I'm also a visual learner, so this was very helpful. I'm still early on with JavaScript and it's challenging to understand it all; are there any books out there for us visual learner that you might recommend?

toanoop profile image
Anoop Sivadas

Try the book written by a John duckett

ocalde profile image
Oscar Calderon

Hi Lydia. Thanks for taking the time of generating these animations in order to explain it in a very simple way. Still, I have doubts regarding the Call Stack. Is it the same as the main thread in which JS runs? I mean, I understood that, although JS is single threaded, but for the asynchronous logic that gets executed, NodeJS would spawn threads for it while processing the main logic in the single thread. Thanks in advance :)

codefinity profile image
Manav Misra

This is a great ❓, but probably gets a bit more 'low-level' than we need to just understand the behavior of our JS code with relation to the event loop.
However, my understanding is that the JS Engine/Runtime Environment consists of only the stack and the heap. The stack is what is 🏃🏽‍♂️on that single thread. Meanwhile, that message queue is part of the asynchronous browser environment. So, JS's single thread runs through call stack on its single thread and then checks that mesage queue to see what else needs to be done on its thread when it has the chance.

avneeshroks profile image

I think in case of NodeJs, it's just the c++ Api's Insted of web/browser's Api.

leandrorodriguesviseu profile image
Leandro Rodrigues

Great article Lydia.
Thanks so much for bring that clear explanation.

rjmunhoz profile image
Rogério Munhoz (Roz)

Awesome article! This has helped me a lot!

I was thinking about translating this series into Brazillian Portuguese. Do you happen to know if anyone has done it yet? Would you mind me doing it (ofc with links to the original series)

ccwukong profile image
Nick Chen

Hi Lydia, I love the series. Just wondering what tool did you use to make those animations? I'm also writing some tech stuff but I can't find a perfect virtualization tool to illustrate my ideas, but your animations really match what I was looking for.

stanleysathler profile image
Stanley Sathler

Thank you so much for the illustrations, Lydia! Very helpful, indeed!

One question: what happens when the main thread is blocked - i.e. the UI freezes? Would the whole interaction within that viewport be blocked - e.g. cursor wouldn't change after hovering a link?

I think I've never faced this situation before, so I'm curious how to identify such situation. Is there any way to simulate a huge processing in order to freeze my UI, just to see that?

Thanks in advance!

brunouyuy profile image

Hi, you can try this:

        function wait5seconds() {
            const plus5seconds = new Date().getTime() + 5000;
            while ( plus5seconds > new Date().getTime() ) {}

            console.log( 'wait5seconds end' );

        function clickHandler() {
            console.log( 'click event' );

        document.addEventListener( 'click',
            clickHandler ); // al comunicarme con la API del DOM estoy saliendo de JS 

        console.log( 'end script execution' );

Execute this script, and press a lot of clicks, the clicks events will appear at the end ( because the dom events are push into the queue.

I think that what you need to take into consideration is when you are performing a task that it might take some time, that might block the UI.

gaurangdhorda profile image

In this particular case de-bouncing is useful when we click on button..

cryptic022 profile image
Pankaj Kumar

Just write a for loop which is printing millions numbers. Call this function on any click function. You will see the effect.

tryjude profile image

I'm not a JS developer but every now and then I have to dig into it. Over the past few years I've read lots of random things about the event loop but this is the first time I've had a clear picture of what's going on in the web browser (via the web api). Thanks!

cncuckoo profile image
Songfeng Li(李松峰) • Edited

Good demonstration! But a little issue exists in my opinion.

The 1st animation, when the respond() function was pushed to the call stack and executed, the setTimeout() function should be pushed into the call stack (and executed) as soon as possible, instead of waited for about 1 second. Because, as the first and only one line code inside the respond() function, the call to setTimeout( ) should be executed immediately at that time. The second argument of setTimeout(), 1000ms, has only to do with how long the timer should be waiting to add the callback to the task queue, it does not have any effect for when the setTimeout() should be pushed into the call stack.

I wish I had made this little issue clear. btw, the last animation has the same issue too. Thank you.

escornwell profile image
Eric Cornwell

Great explanations and descriptions. Interesting to note that in the final example the timer value is unimportant. Someone who is unaware of how the queue works might be surprised to find that a timer value of 0 still logs "Second" last. Which is actually an easy way to yield to the UI during a long-running process if it can be continued via a timer callback, which will happen virtually immediately if the queue is empty.

max_tulian profile image
Max (he/his)

Good post, I really appreciate the effort you do to explain the things :)

banzy profile image

Bravo! It's a great article, exactly what I was looking for showing to my team.
Just an extra consideration, it would be very cool to show a final example when we have actually more than one async item at queue. Taking into consideration different times of response for those functions.

adnanbabakan profile image
Adnan Babakan (he/him)

Hi Lydia
This an amazing visualization and demonstration of JavaScript event loop.

I want to ask you permission to translate this article to Persian (Iran's language) with the original post link of course so this article would be more accessible for other readers.

lydiahallie profile image
Lydia Hallie Author

Sure 😃

jonasroessum profile image
Jonas Røssum

Really nice article!
One thing I was confused about was

invoke bar. bar returns a setTimeout function.

Doesn't setTimeout return an id that you can pass to clearTimeout? 🤔

jagajastic profile image
Ibrahim Joseph M.

Yes, It does Jonas, so lets say

let id = setTimeout( () => {
return "hey"}, 1000);

console.log(id) // you will get 1

let id2 = setTimeout( () => {
return "hey"}, 1000);

console.log(id2) // you will get 2

thamerbelfkihthamer profile image
thamer belfkih

thank guys to point out this detail, in the same context what's the purpose of this Id and it is used by the web API or the call stack for some purpose? thanks in advance

chanmilee profile image
Chanmi Lee

Tons of thanks for this great article and awesome animations! :)
I wonder if it would be possible to translate this article to Korean with the original post link for making this useful content be more accessible for other readers.

hannadrehman profile image
hannad rehman

What if there are no functions is the program?.lets say i have 10 instructions like variable deceleration, assignment , arthematic operations etc. Will all these instructions also go to call stack?
Var a = 10:
Var b;
b = a+ 10;

ruizhen88 profile image

Thanks for the great article, Lydia! Do you mind if I translate this JS Visualizeed series into Korean with the original article and author credit? I think a lot of Korean developers would be interested in learning them.

devworkssimone profile image

I love gifs! Thanks for explanatio ! Not programming in javascript but was very interesting ti read!

avneeshroks profile image

Hey Lydia! This was amazingly explained! One thing I'm still now able to understand is what's microtasks and macrotasks! How engine prioritize those? Also how the Render/Paint queue work with the Normal queue?

evelynpei profile image
Evelyn Pei

Very helpful in further understanding the event loop! Thanks for posting, Lydia! :)

abinash393 profile image

what about microtasks?

douglasfugazi profile image
Douglas Fugazi

Super nice explanation. I've learnt new things with this article. Thanks!

indysigner profile image
Markus Seyfferth

Hi Lydia,

such as great and helpful article! Would it be OK with you to translate it into German and to republish it on (with your author bio, of course)?

Thank you, — Markus

lydiahallie profile image
Lydia Hallie Author


indysigner profile image
Markus Seyfferth

Thanks so much!

gsvidal profile image

Amazing!, it was so helpful, thanks

10secondsofcode profile image
Elango Sundar

Nice awesome articles and visullay explained the event loops :)

ashimb profile image

Fantastic visualization. Thanks Lydia

ryzhov profile image
Aleksandr N. Ryzhov


thecodingalpaca profile image
Carlos Trapet

Good stuff, Lydia! You have a very nice and straight-to-the-point way of expressing concepts, I'd love to read some more posts of yours, if you do have any!

lydiahallie profile image
Lydia Hallie Author

Will post them soon 😎

ijebusoma profile image
Vanessa Osuka

So it's safe to say the purpose of the event loop is to prevent any callback clashes? 🤔

lydiahallie profile image
Lydia Hallie Author

Hm no, not really. Imagine we have 4 tasks, and the 2nd tasks needs a delay. If this delay would've happened on the main thread, nothing would've been able to run on the thread while we were waiting:

However, the web api gives us some sort of asynchronous behavior by letting us put stuff "to the side" so to say. We can now keep on running other tasks, thus keeping an interactive UI, while tasks are running in the background:

Hope this somehow made sense haha I just woke up so my illustrations may not be optimal 😜

stanleysathler profile image
Stanley Sathler

So can we say that preventing callback clashes is the queue's job, instead of event loop's one?

devworkssimone profile image
DevWorksSimone • Edited


kanxiaoxi profile image

Hi, Lydia Hallie, Thank you for your great work. I want to translate your articles in Chinese to improve my English and skills😊.

olesbolotniuk profile image

The best explanation I've ever seen, thank you for sharing!
What's the role of the HEAP that's mentioned on the first picture?

arctekdev profile image
Arctek 🧊

You did a fantastic job of explaining and animating this.

larsolt profile image

Awesome, thanks

deyvisonrocha profile image
Deyvison Rocha

Nice article! Thanks for share!

henshawsamuel profile image
Samuel Henshaw

I was, currently and still impressed and wowwwwwed by this article. its as if this is the first time i am seeing a Promise.

Great article

bigleegeek1 profile image

As a newbie to learning JS I appreciate your post and look forward to others.


rodolphoasb profile image
Rodolpho Bravo

Hey, Lydia! How have you been? Awesome article!!

Can I translate this article series into Portuguese? (With original author and link, of course).

markandersonnc profile image

Great article. JS is so hard to learn

ajay08code profile image

Gifs are so explicit. You really explained everything perfectly

thisisanish profile image
Anish Agarwal

Glad to find such a gem !

frances34983772 profile image
Francesca T

Thanks a lot Lydia!

cagatayunal profile image
Cagatay Unal

Thanks for the great article.

natespring profile image
Nate Spring

The visualization helps so much! Thank you very much for putting the time into this.

rhaegar453 profile image

This is one of the best articles I've seen on Event Loop. Thanks, Lydia for sharing :)

hossammuhammedomar profile image
Hossam Omar

great article, thank you very much

azeem2793 profile image
Agha Azeem

Fantastic 👍

_martinjose28_ profile image
martin jose

And finally i started to understand how the event loop works, thanks a loooot. I've been reading for days feeling confusing. Great job with those gif, love it.

sudharsanansr profile image
Sudharsanan Ravichandran

This is a great article, thanks for sharing!

princebuchi12 profile image
Prince Buchi


trangchongcheng profile image

Nice, thank for you <3

perpetual_education profile image
perpetual . education

Great job! Here's a deep dive from another presenter: - and with a live app to show the visualizations.

rschneider94 profile image
Rodrigo Schneider

Thanks for this article and also the others. Awesome explanation and awesome GIFs! Cool idea. I hope you have a nice day! :)

diebythelaw profile image

Thank you for sharing, it's really interesting!

nhuthuynh profile image

Great article, amazing animations makes me understand the topic easily.

gislenejs profile image
Gislene Carvalho

It's a gift of the Gods for a visual learner like me. Thanks for this ultra helpful article.

djangotricks profile image
Aidas Bendoraitis

These series are such a pearl. Thanks for creating them. I am very happy to have found them.

karthikaruna profile image
Karthikeyan A.

Hey Lydia, what about event listeners/callbacks? How do they work internally?

atilacamurca profile image
Átila Camurça Alves

Great article!

Have you heard of loupe?

sarah_chima profile image
Sarah Chima

Super clear explanation. Thanks for sharing this.

mustafaensar profile image
Mustafa Ensar

Hi Lydia Hallie,

I'm gonna make a presentasion and tell this subject to other students like me in my class. Can I use your gif images :)

sriramvsharma profile image
Sriram Sharma

Lydia, thank you for breaking this down for us! As a visual learner, this is gold!

juliosaraiva profile image
Julio Saraiva

Awesome. Great Job!

wlsdud2194 profile image

Super nice article. Thank you for writing the post😊

I want to translate this post series into Korean. May I do this leaving the link and original author?

yamanchinu profile image
Yaman Agrawal

Lydia, big thanks, I have been coding for a while now, always wished I had some visual guidance at the start of my career and here you are. BIG THANKS AND HUGE RESPECT.

didof profile image
Francesco Di Donato

Hello Lydia,
I really appreciate you piece of work. Congratulations.

paras594 profile image
Paras 🧙‍♂️

good good good...these visualizations are fabulous !!

idaeun profile image
Daeun Kang

Hi, thank you for great article.
Can I translate this series into Korean in my blog? (of course with original author & link)

diepvv profile image

Hi, Lydia, it is a great article.

iakgoog profile image
Sutthinart Khunvadhana

Fantastic article. Love the way you explain things step-by-step.

usepotatoes profile image
Kus Cámara

Great post! Worths mentioning the job or microtask queue (promises) that has higher priority than the callback queue.

jameslam profile image

Great article, thanks! Could you please explain macro task and micro task in this visual way? It can definitely help others!

rmfranciacastillo profile image
Renato Francia Castillo

This is so COOL! What did you used in order to do the animations?

marinaandthecode profile image

Thanks a lot! It doesn't look scary anymore

karthikaruna profile image
Karthikeyan A.

Lydia, what about event callbacks like click, scroll. How do they work?

jongeunk0613 profile image
Jongeun Kim

Hi, Lydia.
Your article was of great help in understanding javascript.

Could I upload your article in Korean translation?
It would greatly help other Korean developers !!

kamilahsantos profile image
Kamila Santos Oliveira

awesome content!

swtpumpkin profile image

This is interesting article!!!
So, i want translate Korean.....
Is it possible?

ximbal profile image

Great Series! Love them, what did you use to create your animations?

anilloutombam profile image
Anil Loutombam

The GIF you put just, make my things so loud and clear, thank you so much.

k96white profile image
Kiran Kamath

Why does event loop makes sure the call stack is empty , if there is already a callback function inside queue waiting to be invoked?

ksdeveloper profile image
kuldeep patel

I really love this article...
My mind is blown. 🤯
This article is very used fully for me. Thank you Lydia Hallie. 🙂