✨♻️ JavaScript Visualized: Event Loop
Lydia Hallie

Lydia Hallie @lydiahallie

About: Software eng who likes to visualize technical concepts in my free time 🕺🏼 (I use Keynote..)

Joined:
Jul 21, 2019

✨♻️ JavaScript Visualized: Event Loop

Publish Date: Nov 20 '19
4398 189

If you're here in 2024 (or later), here's an updated blog post!](https://lydiahallie.com/blog/event-loop)


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 confusing to understand at first. I’m a visual learner so I thought I’d try to help you by explaining it in a visual way through low-res gifs because it's 2019 and gifs are somehow still pixelated and blurry.

But first, what is the event loop and why should you care?

JavaScript is single-threaded: only one task can run at a time. Usually that’s no big deal, but now imagine you’re running a task which takes 30 seconds.. Ya.. During that task we’re waiting for 30 seconds before anything else can happen (JavaScript runs on the browser’s main thread by default, so the entire UI is stuck) 😬 It’s 2019, no one wants a slow, unresponsive website.

Luckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior 🚀

When we invoke a function, it gets added to something called the call stack. The call stack is part of the JS engine, this isn’t browser specific. It’s a stack, meaning that it’s first in, last out (think of a pile of pancakes). When a function returns a value, it gets popped off the stack 👋

The respond function returns a setTimeout function. The setTimeout is provided to us by the Web API: it lets us delay tasks without blocking the main thread. The callback function that we passed to the setTimeout function, the arrow function () => { return 'Hey' } gets added to the Web API. In the meantime, the setTimeout function and the respond function get popped off the stack, they both returned their values!

In the Web API, a timer runs for as long as the second argument we passed to it, 1000ms. The callback doesn’t immediately get added to the call stack, instead it’s passed to something called the queue.

This can be a confusing part: it doesn't mean that the callback function gets added to the callstack(thus returns a value) after 1000ms! It simply gets added to the queue after 1000ms. But it’s a queue, the function has got to wait for its turn!

Now this is the part we’ve all been waiting for… Time for the event loop to do its only task: connecting the queue with the call stack! If the call stack is empty, so if all previously invoked functions have returned their values and have been popped off the stack, the first item in the queue gets added to the call stack. In this case, no other functions were invoked, meaning that the call stack was empty by the time the callback function was the first item in the queue.

The callback is added to the call stack, gets invoked, and returns a value, and gets popped off the stack.


Reading an article is fun, but you'll only get entirely comfortable with this by actually working with it over and over. Try to figure out what gets logged to the console if we run the following:




const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");

bar();
foo();
baz();


Enter fullscreen mode Exit fullscreen mode

Got it? Let's quickly take a look at what's happening when we're running this code in a browser:

  1. We invoke bar. bar returns a setTimeout function.
  2. The callback we passed to setTimeout gets added to the Web API, the setTimeout function and bar get popped off the callstack.
  3. The timer runs, in the meantime foo gets invoked and logs First. foo returns (undefined),baz gets invoked, and the callback gets added to the queue.
  4. baz logs Third. The event loop sees the callstack is empty after baz returned, after which the callback gets added to the call stack.
  5. The callback logs Second.

Hope that this makes you feel a bit more comfortable with the event loop! Don't worry if it still seems confusing, the most important thing is to understand where certain errors/behavior can come from in order to Google the right terms efficiently and end up on the correct Stack Overflow page 💪🏼 Feel free to reach out to me if you have any questions!

Comments 189 total

  • Carlos Trapet
    Carlos TrapetNov 20, 2019

    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!

  • Dayvster 🌊
    Dayvster 🌊Nov 20, 2019

    You did a fantastic job of explaining and animating this.

  • Max (he/his)
    Max (he/his)Nov 20, 2019

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

  • Rafael Beckel
    Rafael BeckelNov 20, 2019

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

    • Lydia Hallie
      Lydia HallieNov 20, 2019

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

      • squidbe
        squidbeNov 25, 2019

        Professional enough!

  • Elango Sundar
    Elango SundarNov 21, 2019

    Nice awesome articles and visullay explained the event loops :)

  • thebilson
    thebilsonNov 21, 2019

    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?

  • Vanessa Osuka
    Vanessa OsukaNov 21, 2019

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

    • Lydia Hallie
      Lydia HallieNov 21, 2019

      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 😜

      • Stanley Sathler
        Stanley SathlerNov 21, 2019

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

      • DevWorksSimone
        DevWorksSimoneNov 21, 2019

        Great!

  • Stanley Sathler
    Stanley SathlerNov 21, 2019

    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!

    • Pankaj Kumar
      Pankaj KumarDec 14, 2019

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

    • bru
      bruJan 21, 2020

      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 
      
              wait5seconds();
              console.log( 'end script execution' );
      
      Enter fullscreen mode Exit fullscreen mode

      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
        GaurangDhordaJan 28, 2020

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

  • DevWorksSimone
    DevWorksSimoneNov 21, 2019

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

  • Eugene Karataev
    Eugene KarataevNov 22, 2019

    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.

  • Logan
    LoganNov 22, 2019

    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).

  • Jonas Røssum
    Jonas RøssumNov 23, 2019

    Really nice article!
    One thing I was confused about was

    invoke bar. bar returns a setTimeout function.
    
    Enter fullscreen mode Exit fullscreen mode

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

    • Ibrahim Joseph
      Ibrahim JosephNov 26, 2019

      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
      
      
      • thamer belfkih
        thamer belfkihFeb 2, 2020

        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

  • Douglas Fugazi
    Douglas FugaziNov 25, 2019

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

  • bigleegeek1
    bigleegeek1Nov 25, 2019

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

    bigleegeek

  • Adnan Babakan (he/him)
    Adnan Babakan (he/him)Nov 25, 2019

    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.

  • Lars
    LarsNov 25, 2019

    Awesome, thanks

  • Leandro Rodrigues
    Leandro RodriguesNov 25, 2019

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

  • Deyvison Rocha
    Deyvison RochaNov 26, 2019

    Nice article! Thanks for share!

  • Aleksandr N. Ryzhov
    Aleksandr N. RyzhovNov 26, 2019

    Thanks!

  • Markus Seyfferth
    Markus SeyfferthNov 26, 2019

    Hi Lydia,

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

    Thank you, — Markus

  • Abinash Panda
    Abinash PandaNov 26, 2019

    what about microtasks?

  • Agha Azeem
    Agha AzeemNov 27, 2019

    Fantastic 👍

  • Jude
    JudeNov 27, 2019

    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!

  • Marina
    MarinaNov 27, 2019

    Thanks a lot! It doesn't look scary anymore

  • oles-bolotniuk
    oles-bolotniukNov 28, 2019

    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?

  • Oscar Calderon
    Oscar CalderonNov 29, 2019

    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 :)

    • Manav Misra
      Manav MisraMar 10, 2020

      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
      avneeshroksDec 19, 2020

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

      • SebasQuiroga
        SebasQuirogaDec 3, 2021

        Hi @avneeshroks , I have recently cloned and run the NodeJS code and effectively C/C++ are dominant.
        Remember that NodeJS is on top of the V8 engine (the one used in the Chrome browser) that Google opensourced and it is natively written in C++, running in the browser and running in a server are two different environments with different purposes and indeed different APIs. NodeJS is literally running on the same engine than Chrome, but for NodeJS it is not needed to have APIs such as those for the DOM, Window, etc as Chrome needs.

  • Sutthinart Khunvadhana
    Sutthinart KhunvadhanaDec 3, 2019

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

  • perpetual . education
    perpetual . educationDec 5, 2019

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

  • Kus Cámara
    Kus CámaraDec 23, 2019

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

  • martin jose
    martin joseJan 6, 2020

    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.

  • Átila Camurça Alves
    Átila Camurça AlvesJan 10, 2020

    Great article!

    Have you heard of loupe? latentflip.com/loupe/

  • JeongwonKim
    JeongwonKimJan 16, 2020

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

  • NhutHuynh
    NhutHuynhJan 18, 2020

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

  • Rodrigo Schneider
    Rodrigo SchneiderJan 20, 2020

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

  • Gislene Carvalho
    Gislene CarvalhoJan 22, 2020

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

  • Sarah Chima
    Sarah ChimaJan 23, 2020

    Super clear explanation. Thanks for sharing this.

  • JinYoung-Lee
    JinYoung-LeeJan 27, 2020

    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?

  • Aidas Bendoraitis
    Aidas BendoraitisJan 27, 2020

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

  • Yejin
    YejinJan 30, 2020

    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.

  • Shriram Sharma
    Shriram SharmaJan 31, 2020

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

  • hannad rehman
    hannad rehmanFeb 1, 2020

    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;

    • Jeannot MN
      Jeannot MNSep 13, 2022

      These will be executed in the global execution context... which is at the bottom of your call stack

  • Songfeng Li(李松峰)
    Songfeng Li(李松峰)Feb 5, 2020

    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.

  • Francesco Di Donato
    Francesco Di DonatoFeb 12, 2020

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

  • Renato Francia Castillo
    Renato Francia CastilloFeb 18, 2020

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

  • Mustafa Ensar
    Mustafa EnsarFeb 21, 2020

    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 :)

  • Rogério Munhoz (Roz)
    Rogério Munhoz (Roz)Feb 25, 2020

    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)

  • Diego Palacios Lepore
    Diego Palacios LeporeMar 4, 2020

    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:

    latentflip.com/loupe

    • Shelby Anne
      Shelby AnneSep 1, 2022

      woah that tool is awesome!

    • Muhammad Ayaz
      Muhammad AyazDec 9, 2022

      The tool is amazing, if we have 2 aysnc functions, the web api section will only show the latest one

    • Sherlock
      SherlockMar 25, 2023

      Amazing tooling!!!

    • Miodrag Dzamic
      Miodrag DzamicMar 2, 2024

      I tried to copy paste some code into tool and it does not save after clicking Save+Run button. Does someone else has same issue? Thanks!

  • jameslam
    jameslamMar 26, 2020

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

  • Yaman Agrawal
    Yaman AgrawalMar 29, 2020

    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.

  • Vicent
    VicentApr 6, 2020

    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.

  • Julio Saraiva
    Julio SaraivaApr 10, 2020

    Awesome. Great Job!

  • Samuel Henshaw
    Samuel HenshawApr 15, 2020

    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

  • Paras 🧙‍♂️
    Paras 🧙‍♂️Apr 16, 2020

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

  • Rodolpho Bravo
    Rodolpho BravoApr 21, 2020

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

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

  • cucheng
    cucheng Apr 26, 2020

    Nice, thank for you...love you <3

  • Vandstein
    VandsteinApr 30, 2020

    Thank you for sharing, it's really interesting!

  • Prince Buchi
    Prince BuchiMay 1, 2020

    Wow

  • Karthikeyan A.
    Karthikeyan A.May 1, 2020

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

  • Karthikeyan A.
    Karthikeyan A.May 1, 2020

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

  • diepvv
    diepvvMay 5, 2020

    Hi, Lydia, it is a great article.

  • Anil Loutombam
    Anil LoutombamMay 7, 2020

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

  • Daeun Kang
    Daeun KangMay 13, 2020

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

  • Eric Cornwell
    Eric CornwellMay 17, 2020

    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.

  • Chanmi Lee
    Chanmi LeeJun 7, 2020

    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.

  • Sudharsanan Ravichandran
    Sudharsanan RavichandranJul 6, 2020

    This is a great article, thanks for sharing!

  • Kamila Santos Oliveira
    Kamila Santos OliveiraJul 23, 2020

    awesome content!

  • Hossam Omar
    Hossam OmarAug 2, 2020

    great article, thank you very much

  • Evelyn Pei
    Evelyn PeiSep 18, 2020

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

  • rhaegar453
    rhaegar453Sep 22, 2020

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

  • EN
    ENDec 10, 2020

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

  • avneeshroks
    avneeshroksDec 19, 2020

    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?

  • Jongeun Kim
    Jongeun KimDec 31, 2020

    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 !!

  • kuldeep patel
    kuldeep patelJan 1, 2021

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

  • Nate Spring
    Nate SpringJan 5, 2021

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

  • Cagatay Unal
    Cagatay UnalMar 31, 2021

    Thanks for the great article.

  • Francesca  T
    Francesca TApr 9, 2021

    Thanks a lot Lydia!

  • Anish Agarwal
    Anish AgarwalApr 13, 2021

    Glad to find such a gem !

  • ajay08-code
    ajay08-codeApr 28, 2021

    Gifs are so explicit. You really explained everything perfectly

  • MarkAndersonNC
    MarkAndersonNCMay 5, 2021

    Great article. JS is so hard to learn

  • Gonzalo
    GonzaloMay 16, 2021

    Amazing!, it was so helpful, thanks

  • 侃小溪
    侃小溪Jun 3, 2021

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

  • A5h1m
    A5h1mJun 6, 2021

    Fantastic visualization. Thanks Lydia

  • Nick Chen
    Nick ChenJun 10, 2021

    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.

  • Kiran Kamath
    Kiran KamathJun 30, 2021

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

  • Rishav Kumar
    Rishav KumarOct 5, 2021

    Hi, Lydia Hallie, this is a really informative article.
    Please make a similar article on event loop in Node.js if possible.
    It will be of immense importance to me as I am unable to get a proper explanation with an example.

  • Vikas Chauhan
    Vikas ChauhanOct 6, 2021

    This is the best article on event loop I have encounter so far.
    Thank you so much for making it so wasy for us :-)

  • MOHAMED ZABOUB
    MOHAMED ZABOUBOct 23, 2021

    I just wanna thank you for this amazing explanation, the first time I've read this 3 months ago, everything was new to me and blur.

    Today I went on it again and it's just crystal clear too!

    Thank you 3

  • i love Math
    i love MathNov 18, 2021

    Hi, Lydia Hallie
    you mentioned "web API" so what do you mean "web API"? I don't understand what "web API" is, which you are referring to?

  • i love Math
    i love MathNov 18, 2021

    hi Lydia
    you mentioned "web API" so what do you mean "web API"? I don't understand what is "web API" , which you are referring to?

  • SebasQuiroga
    SebasQuirogaDec 3, 2021

    Great article Lydia!

  • Syed Mustafa Naqvi
    Syed Mustafa NaqviJan 26, 2022

    Hi, Lydia Hallie can you tell me what is the case with setInterval in call stack a combination of setTimeout and setInterval see the usecase below. Is setInterval also supposed to go to webAPI?

    
    
    let c = 0;
    let id = setInterval(()=> {
    console.log(c++)
    },200)
    
    setTimeout(()=> {
    clearInterval(id)
    },2000)
    // prints
    /* 0
    1
    2
    3
    4
    5
    6
    7
    8 
    9
    and then stops  */
    
    Enter fullscreen mode Exit fullscreen mode
    • Maksim Rozhkov
      Maksim RozhkovFeb 15, 2023

      2000/200 = 10 times

      after 2 seconds we clear setInterval id

  • Bilal Niaz
    Bilal Niaz Jan 28, 2022

    Hi, Lydia Hallie, it's good article

  • islam saeed
    islam saeedFeb 1, 2022

    👍 the best one explained event loop ➿

  • Esteban Vera
    Esteban VeraFeb 22, 2022

    Hi, Lydia!
    You are the best!

  • Monish Soni
    Monish SoniApr 25, 2022

    Thank You so Much !!

  • khaled-alwakel
    khaled-alwakelJul 17, 2022

    thank you so much . it was very helping ..

  • Jeannot MN
    Jeannot MNJul 28, 2022

    Thanks for the detailed post😃.

    I have a question regarding this "Luckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior 🚀"

    Does the Web API allow us to create asynchronous behavior? Doesn't it just give us features that the JS Engine does not have?
    Am I wrong saying it's rather the event loop and the callback queue that allow us to create asynchronous behavior?

  • Jeff Chavez
    Jeff ChavezAug 13, 2022

    Wow. This is so helpful since JS is really challenging. Thanks for the effort.

  • Darshit Gajjar
    Darshit GajjarAug 13, 2022

    Great Article Lydia, make this kind of Articles ❤️

  • crazy4groovy
    crazy4groovyAug 13, 2022

    Thanks!

    Now it time to add the promise's micro queue! :)

  • Sachintha Dhananjana
    Sachintha DhananjanaAug 14, 2022

    This is a Great job.It makes really easy to understand the concept.

  • Upasana Mahanta
    Upasana MahantaAug 14, 2022

    Great article and animations!

  • Omar Pervez
    Omar PervezAug 14, 2022

    It's great article I saw. I have no more confused about it. I was trying to learn it but I can't. but Thank God, That I got your article on my browser home page. I want to also thank you daily.dev. they saw your article on my home page and I have come to your article and learned about event loop. Again Thank you so much Lydia Hallie from Omar.

  • Karim Muhammad
    Karim MuhammadAug 14, 2022

    I have question here...

    function hello() { // sync
    console.log("hello");
    }
    function afterWhile() { async
      setTimeout(()=> {
        console.log("After Timer")
      }, 0)
    }
    afterWhile();
    
    hello();  // gets added in callstack then pop it out sequentally;
    // so callstack is empty here, i guess?!!!! so why callback hasn't been executed here, in this time
    
    hello();
    
    Enter fullscreen mode Exit fullscreen mode

    callstack here carry on one task then remove it, so why callback hasn't executed after popping out instanctly?

    • Jeannot MN
      Jeannot MNSep 13, 2022

      Functions are pushed into the the call stack when the callstack is empty AND there are no other line of code to be executed in the main thread... in your case it was not pushed because there was still one more thing to execute in the main thread of execution (the second hello()); Only after completing the second call to the hello function that your callback will be pushed into the callstack...

      I hope this helps.

  • Hagay Haut
    Hagay HautAug 15, 2022

    Thanks for putting these together! I've been reading about some of this stuff and this really helps it click.

  • mohmmadmoussa1988
    mohmmadmoussa1988Aug 16, 2022

    Great Visuals, Thank you

  • Abdallah Samir
    Abdallah SamirAug 17, 2022

    please i need to know how it works with more than async operation
    such as 2 of setInterval or 2 of setTimeout

    Thank you

  • Robson Muniz
    Robson MunizAug 19, 2022

    Wow, Great Contet, thanks for sharing it!

  • ehza
    ehzaAug 20, 2022

    This is fantastic!

  • capscode
    capscodeSep 21, 2022

    Wow...
    Amazing article for and amazing topic of JS by an amazing writer with an amazing explanation.

    thanks for sharing this.

  • Ramy Sabry
    Ramy SabrySep 29, 2022

    Hi, Lydia Hallie, it is a great article.
    Thanks so much, finally i understand it.

  • Tu Nguyen
    Tu NguyenNov 21, 2022

    It is a very visual and great, easy to understand, you saved my life.
    Hungry to read these kind of posts.

    Love your post!!!!

  • NovaJay2415
    NovaJay2415Nov 22, 2022

    Super helpful! I love this!

  • Fernando Rodrigues
    Fernando RodriguesNov 30, 2022

    I love it! I’m a visual learner too so this helps a lot! Keep going! o/

  • EdgarMC100
    EdgarMC100Dec 14, 2022

    This article helped me to remember what I read in a book in just 5 minutes, thanks Lydia. I consider myself a visual learner.

  • Don Jude Joseph
    Don Jude JosephDec 26, 2022

    Thank you Lydia Hallie fo this article

  • Ester Kaufman
    Ester KaufmanJan 12, 2023

    Hi, Lydia, i think this is the best post to get the JS loop behind the scenes.

    Can I translate this post, and publish it on my blog, with credits to the author and direct link?
    Thanks for posting!

  • Soe Moe Htet
    Soe Moe HtetJan 16, 2023

    Thanks for a great article series. 👍

  • Tamb
    TambJan 19, 2023

    You explained this beautifully! Thank you!

  • Prafulla Raichurkar
    Prafulla RaichurkarJan 25, 2023

    Wow, nicely explained :D

  • thanhtrung
    thanhtrungFeb 3, 2023
    1. The timer runs, in the meantime foo gets invoked and logs First. foo returns (undefined),baz gets invoked, and the callback gets added to the queue.

    Image description
    I don't understand why it can log undefined in here, can you pls explain more ?

  • Khiêm
    KhiêmFeb 13, 2023

    Awesome!

  • El-amiir
    El-amiirFeb 14, 2023

    Great article, Thanks.

  • kazinoman
    kazinomanFeb 25, 2023

    Tnx for your effort.

  • Trần Đức Hòa
    Trần Đức HòaFeb 28, 2023

    Great article! Thanks.

  • ᴏɴᴇꜱ ᴅɪᴏᴜᴀɴɪ
    ᴏɴᴇꜱ ᴅɪᴏᴜᴀɴɪMar 7, 2023

    Great article
    Thanks Lydia

  • zhangbowy
    zhangbowyMar 21, 2023

    Can I translate your article to a Chinese technical website? , will comment the original link

  • Rash Edmund
    Rash EdmundApr 8, 2023

    thanks @lydiahallie

  • Jatin Kumar
    Jatin KumarApr 15, 2023

    Very informative. Hats off to the explanation!!!

  • Diana Lozano
    Diana LozanoApr 28, 2023

    Looks like "What the heck is the event loop anyway?" by Philip Roberts | JSConf EU
    https://www.youtube.com/watch?v=8aGhZQkoFbQ&vl=en

  • Ramiro
    RamiroMay 12, 2023

    excelente articulo, pensar que hace unos meses no entendia nada pero guarde el articulo ya que sabia que esto era clave, y ahora de tanto repasar js vanilla, pude entender jeje saludos desde la Patagonia, argentina.

  • aaktansel
    aaktanselMay 21, 2023

    Hi Lydia ,

    Thanks for this useful article explaning a difficult to understand concept in a very simple way. And i want to translate it to Turkish to share in my personal blog, with linking the original author, do you have permission for this?

  • Doston
    DostonJun 4, 2023

    Hello , Lydia Hallie, it is a great article.

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

  • Hieu Nghia
    Hieu NghiaJun 22, 2023

    nice****

  • Chidera Humphrey
    Chidera HumphreyJun 27, 2023

    Super helpful and well written.

    Thanks for taking your time to share this with us.

  • Pratap Sharma
    Pratap SharmaAug 13, 2023

    Hi @lydiahallie It was an amazing article and animations.

    How did you create those animations?

  • STARK
    STARKAug 17, 2023

    I just can't believe how ellaborate and simple this blog is !!!.This seriously made my day and saved me a lot of time.kudos to the writer!! I specifically created an account to make this comment to support this author.Expecting a lot of concepts to be simplified with gif's.

  • DangNguyen
    DangNguyenOct 5, 2023

    Amazing, really like you visualization

  • PRAJWAL PATIL
    PRAJWAL PATILNov 15, 2023

    Nicely explained.. thank you so much

  • Johannes
    JohannesJan 2, 2024

    Hi Lydia,

    I'm refreshing my knowledge on the event loop and even though your article is mostly correct, it does not start strong with the incorrect statement:

    The respond function returns a setTimeout function.

    This is incorrect. The respond will return an integer. You can easily check this yourself by doing:

    const returned = respond();
    console.log(returned === parseInt(returned)) // true
    
    Enter fullscreen mode Exit fullscreen mode
  • asuna24
    asuna24Feb 23, 2024

    Hi @lydiahallie , thank you for your super comprehensive explanation. All of the gifs are incredible, helped me a lot to understand more about javascript under the hood.

  • Oussama
    OussamaFeb 25, 2024

    very insightful thank you

  • Maysam
    MaysamMar 26, 2024

    wow!

  • Gabrielduerto
    GabrielduertoApr 6, 2024

    Muchas Gracias Lydia, aunque no pude entender tu video, el texto esta bien explicado y pude traducirlo, se que tengo que aprender Ingles, tan pronto termine el bootcamp hare un curso intensivo de Ingles, igualmente muchas Gracias por tu Articulo <3

  • Gizela Delgado Soto
    Gizela Delgado SotoApr 8, 2024

    This is really usuful, the graphics help a lot 🤗

  • Devidmaul
    DevidmaulApr 22, 2024

    Still learning Java. It's little bit difficult for me. I used it on my project Infinite Craft

  • leon
    leonApr 30, 2024

    Hi, Hallie, I think you can add 'async/await' execute in the gif.

  • Prasath
    PrasathMay 17, 2024

    The article is excellent and the video explanation is truly remarkable.!

  • Ajas
    AjasMay 31, 2024

    The Best.

  • Imtiaz Ali
    Imtiaz AliJun 11, 2024

    I am learning through your github repository Javascript Questions.
    The all I have to say you made my life It's helping me alot to understading the javascript.
    In one of those questions you shared the link of this article it's just an amazing stuff you shared on github thank you so much.

  • Saulius
    Saulius Jun 17, 2024

    Superb!

  • Dohn Joe
    Dohn JoeAug 21, 2024

    Thanks!!!! This article is amazing 👏👏👏

  • Mohammad Reza Ghasemi
    Mohammad Reza GhasemiSep 8, 2024

    Hey Lydia, just wanted to say a huge thank you for this series. I really appreciate it and now I feel like I've got a good grasp on these JavaScript concepts.

  • Deepak Vishwakarma
    Deepak VishwakarmaSep 12, 2024

    i read it 1month earlier thank you for quick revision it,s great your written article feel like somebody teaching in front of me easy english

  • maedehjavadi
    maedehjavadiOct 19, 2024

    This is the greatest article about Event Loop I've ever seen. You provided a complete explanation in a short time—perfect!
    I hope you keep providing these videos, they are useful for every web developer.

  • Ibtesum Reza Aninda
    Ibtesum Reza AnindaOct 21, 2024

    Image no longer exists!!!!!

  • LaercioLopesLL
    LaercioLopesLLOct 21, 2024

    Images off

  • Ishan Bagchi
    Ishan BagchiAug 4, 2025

    Hi Lydia, I watched your video and found it really informative. I’ve come across a few Event Loop visualizers before, but none of them really clicked for me, so I ended up building my own: event-loop-visualiser.ishanbagchi.com. Hope the community finds it useful! 😊

Add comment