DEV Community

Cover image for JS illustrated: The event loop 🔁

JS illustrated: The event loop 🔁

John Kapantzakis on August 15, 2019

Javascript is single threaded, yet, developers can write asynchronous code in Javascript! But how is it possible? The event loop makes it possible...
Collapse
 
q3flat profile image
q3flat

Very nice article! Thank you for your effort!

Collapse
 
kapantzak profile image
John Kapantzakis

Thank you very much!

Collapse
 
vikaschauhan1 profile image
Vikas Chauhan

One of the greatest articles to clear all the doubts about event loop.
Thanks man

Collapse
 
amineamami profile image
amineamami

Great article, but one question how’s this asynchronous ?

Collapse
 
kapantzak profile image
John Kapantzakis

Thanks @amineamami !
According to MDN: Asynchronous , asynchronous code may refer to multiple related tasks happening without waiting for each other to complete.

In our case, if the code was not asynchronous, the setTimeout call whould have blocked the execution of the program until it was completed printing "Two" at the console.

But this is not the case. The program continues executing, printing "three" and, after that, the callback of the setTimeout is called, printing "Two" at the end.

Collapse
 
amineamami profile image
amineamami • Edited

Hmm, it seemed to me just like synchronous execution with a bit of instructions reordering.

Thread Thread
 
kapantzak profile image
John Kapantzakis • Edited

Thats right! Javascript language itself does not have any asynchrony built in.
The environment (browser, node etc) is the one that arranges the events resulting in asynchronous execution (the use o callbacks, promises, ajax calls etc)

Collapse
 
sepsol profile image
Sepehr Soltanieh

Awesome! Maybe make it a gif someday?!

Collapse
 
sborsay profile image
Stephen Borsay

Hi,

On your description it shows the Web API putting "two" on the message queue but when the message is extracted from the message queue you are showing that is done by the event loop instead, Is this correct? Does the Web API always push to the message queue while the event loop extracts from the queue, or are you just missing showing the web API managing the both inserting and extracting to the message queue after being triggered by the event loop?

Collapse
 
mohamedneddam profile image
mohamedNeddam

Thank you

Collapse
 
ghostcode profile image
Zhuxy

cool

Collapse
 
asankulovt profile image
Талант Асанкулов

Thank you!

Collapse
 
manussakis profile image
Gabriel Manussakis

Awesome, thanks for this article!