Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for ✨♻️ JavaScript Visualized: Event Loop
Lydia Hallie
Lydia Hallie

Posted on • Edited on

     

✨♻️ JavaScript Visualized: Event Loop

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 issingle-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 👋

Therespond function returns asetTimeout function. ThesetTimeout 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 thesetTimeout function, the arrow function() => { return'Hey' } gets added to the Web API. In the meantime, thesetTimeout 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 thequeue 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 isempty, so if all previously invoked functions have returned their values and have been popped off the stack, thefirst 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:

constfoo=()=>console.log("First");constbar=()=>setTimeout(()=>console.log("Second"),500);constbaz=()=>console.log("Third");bar();foo();baz();
Enter fullscreen modeExit 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 invokebar.bar returns asetTimeout function.
  2. The callback we passed tosetTimeout gets added to the Web API, thesetTimeout function andbar get popped off the callstack.
  3. The timer runs, in the meantimefoo gets invoked and logsFirst.foo returns (undefined),baz gets invoked, and the callback gets added to the queue.
  4. baz logsThird. The event loop sees the callstack is empty afterbaz returned, after which the callback gets added to the call stack.
  5. The callback logsSecond.

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 tounderstand where certain errors/behavior can come from in order toGoogle 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!

Top comments(186)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
logan70 profile image
Logan
  • Location
    ShenZhen,China
  • Work
    Front-end Enginner at ShenZhen,China
  • Joined

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

CollapseExpand
 
lydiahallie profile image
Lydia Hallie
Software eng who likes to visualize technical concepts in my free time 🕺🏼 (I use Keynote..)
  • Joined

Absolutely!

CollapseExpand
 
Sloan, the sloth mascot
Comment deleted
CollapseExpand
 
diegolepore profile image
Diego Palacios Lepore
  • Joined

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

CollapseExpand
 
q118 profile image
Shelby Anne
  • Joined

woah that tool is awesome!

CollapseExpand
 
ayaz profile image
Muhammad Ayaz
I am a skilled Web3 developer with expertise in building decentralized applications (dApps), smart contracts, and blockchain integrations. Let's Connect :https://www.linkedin.com/in/ayazflipsbiz/
  • Email
  • Location
    Islamabad
  • Work
    Full Stack Developer | WEB3 | AI | PMP
  • Joined

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

CollapseExpand
 
sherlockliu profile image
Sherlock
  • Joined

Amazing tooling!!!

CollapseExpand
 
miodragdz profile image
Miodrag Dzamic
  • Joined

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!

CollapseExpand
 
karataev profile image
Eugene Karataev
undefined is not a function
  • Location
    Russia, Novosibirsk
  • Joined

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.

CollapseExpand
 
rafaelbeckel profile image
Rafael Beckel
Dad, Entrepreneur, Software Engineer, Hacker and Tinkerer
  • Location
    Germany
  • Work
    Software Engineer at NewStore
  • Joined

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

CollapseExpand
 
lydiahallie profile image
Lydia Hallie
Software eng who likes to visualize technical concepts in my free time 🕺🏼 (I use Keynote..)
  • Joined

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

CollapseExpand
 
squidbe profile image
squidbe
  • Joined

Professional enough!

CollapseExpand
 
thebilson profile image
thebilson
Hello world!I'm Bill and I recently decided to stop making excuses and start learning to code. It's good to be here.
  • Location
    Buffalo, NY
  • Work
    Technical Recruiter at ComputerPeople Staffing
  • Joined

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?

CollapseExpand
 
toanoop profile image
Anoop Sivadas
I' m a software Developer working in IBM Mainframe technology stack
  • Joined

Try the book written by a John duckett

CollapseExpand
 
ocalde profile image
Oscar Calderon
  • Location
    El Salvador
  • Work
    Senior Backend Developer at NY Startup
  • Joined

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

CollapseExpand
 
codefinity profile image
Manav Misra
I'm a JS Subject Matter Expert (SME) that has spent the past few years spearheading curricula and teaching initiatives at colleges and bootcamps, in person and virtually.
  • Location
    62236
  • Education
    BS - Mech. Eng. - Missouri S&T
  • Joined

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.

CollapseExpand
 
avneeshroks profile image
avneeshroks
  • Joined

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

CollapseExpand
 
sebasqui profile image
SebasQuiroga
I am a software engineer focus on developing robust systems in the cloud and sometimes even on earth.
  • Location
    Colombia
  • Work
    SW Specialist
  • Joined

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.

CollapseExpand
 
rjmunhoz profile image
Rogério Munhoz (Roz)
  • Location
    São Paulo
  • Work
    Software Engineer
  • Joined

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)

CollapseExpand
 
tryjude profile image
Jude
Server developer using Python, Java, Postgres, Oracle... and aspiring Kotlin/Android wannabe
  • Joined

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!

CollapseExpand
 
miwsyed profile image
Syed Mustafa Naqvi
  • Joined

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/* 012345678 9and then stops  */
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
1option profile image
Maksim Rozhkov
  • Joined
• Edited on• Edited

2000/200 = 10 times

after 2 seconds we clear setInterval id

CollapseExpand
 
rodrigues profile image
Leandro Rodrigues
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

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

More fromLydia Hallie

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp