DEV Community

Cover image for Understanding Asynchronous Programming in JavaScript: Beginner's Guide to the Event Loop

Understanding Asynchronous Programming in JavaScript: Beginner's Guide to the Event Loop

Emmanuel Ayinde on September 10, 2024

Have you ever wondered why some pieces of JavaScript code seem to run out of order? The key to understanding this is the event loop. JavaScript's ...
Collapse
 
imkrunalkanojiya profile image
Krunal Kanojiya • Edited

Great information🀘🏻🀘🏻. Little suggestion for your upcoming article, Use images or gifs. That takes your article on top. Waiting for your next article..

Collapse
 
emmanuelayinde profile image
Emmanuel Ayinde

Thanks for the suggestion, Krunal

Collapse
 
ramrapolu profile image
Ram Chandhar Rapolu

Such articles worth reading

Collapse
 
emmanuelayinde profile image
Emmanuel Ayinde

Thank you, Chandhar

Collapse
 
rogeclash_4ac7756ff985814 profile image
RogeClash

amazing article thank you

Collapse
 
emmanuelayinde profile image
Emmanuel Ayinde

Thank you, RogeClash

Collapse
 
daniel_adewole_732e7f1aad profile image
Daniel Adewole

Great and straight to the point. Loved reading it. Kudos

Collapse
 
emmanuelayinde profile image
Emmanuel Ayinde

Thank you for your feedback, Daniel 😁

Collapse
 
mohsin04 profile image
Mohsin Nawaz

Why in the last examples, the fallback setTimeOut executed first?

Collapse
 
emmanuelayinde profile image
Emmanuel Ayinde

The reason the "fallback setTimeout" (i.e., Step 6: Immediate (using setTimeout with 0 delay as fallback)) is executed before Step 5: Timeout 2 has to do with when each setTimeout is added to the macrotask queue (scheduled).

Since Step 5: Timeout 2 was inside a setTimeout (a macrotask) and was called within a promise (a microtask), it experienced a delay before being scheduled. Meanwhile, Step 6: Immediate (using setTimeout with 0 delay as fallback) was called outside of a promise and was scheduled immediately.

What this means is that the second setTimeout (Step 5) was delayed, while the first setTimeout (Step 6) was processed right away.

I hope this explanation clarifies things better!

Collapse
 
shyamsundersrd profile image
Shyamsunder karanam

For Macro tasks, in the definition, it's mentioned that they are executed before next event loop but in the comparison table it's mentioned executed in the next event loop! Which one is correct?