Javascript’s event loop

“Don’t put bad, synchronous code on the call back stack because it prevents a fast, crisp user interface.” 

I used to think javascript is a janky, annoying-to-use language that was a waste of my time. It’s single-threaded async nature, and Node.js’s fast C++ libraries are a good reason as to why websites today feel so much faster. I studied how JS works, because I was interested in node.js and I actually have changed my mind. It’s like python, for web-dev, but really fast.

The call-stack is different than any other modern programming language. In Python or C++, code executes sequentially so that whenever you make a call, you can guarantee that the variable will take on that value when you reference it later in the program. That is why thinking aynchonously can be so hard – our traditional programming paradigms are called into question.

In Javascript, you can and should run things aynchonously so that it doesn’t block the webpage’s render. That render is what makes websites feel more responsive. Writing slow, synchronous code just feels wrong for web-dev.

This all works with something called the event loop, which manages the call-stack. It processes different instructions, in a loop until it is empty. It may be called an event loop because it processes each item in the call-back queue, little by little.

This makes programming very difficult though because now there needs to be a callback function for when a call completes. These callback functions can cause problems like callback hell, where it makes code illegible, bad, and makes us unable to write complex code like Promises.all(). Promises sort of solve this, but the standard today is to use async await – which I need to study a bit more and will write a blog about.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s