Asynchronous Adventures in JavaScript: Understanding the Event Loop

Benjamin Diuguid
DailyJS
Published in
6 min readJan 12, 2016

JavaScript is a powerful language that is eating the world of software development. One of the things that differentiates JavaScript from some of the more “traditional” C-like languages, is how it executes code.

For those unfamiliar with JavaScript, it is often described as having a single-threaded, event-driven, and non-blocking I/O model. This jargon-loaded phrase can be a confusing for those unfamiliar with the JavaScript runtime.

I know there are a lot of great examples and analogies of how the Event Loop works with JavaScript (in the Browser, and in Node), so I will try to break it down in as simply as possible.

An Analogy

Set Up

So let’s say you founded a successful startup, which is a Unicorn 🦄 and was acquired by a very prosperous company. Now with your previously acquired wealth you decide to purchase an island. You decide to name this island JSland. Upon arriving on the island, you discover that it comes with a Minion named Sam. Sam agrees to carry out tasks and errands for you in return for payment in Bananas. 🍌

Sam

Some time later…

You wake up one morning with the following tasks/errands for Sam:

  1. Take out the trash.
  2. Find the answer to the question “What kind of Bear is Best?” (https://youtu.be/zsGnFExpup8)
  3. Get your clothes dry-cleaned (The dry-cleaners is not on the island).
  4. Retrieve a magical rock from the top of MountainJS on the Island.

Task Breakdown

Task 1: Take out the trash.

This is simple for Sam, he will simply run around the various distributed rooms around the house collecting all of the garbage, and dispose of it in the JSland’s Garden. (Note: Everything on JSland is reclaimable, and therefore bio-degradable.)

Task 2: Find the answer to the question “What kind of Bear is Best?

This one is more difficult for Sam. Tired of your constantly connected lifestyle, JSland does not have any internet (The Horror!). Sam must travel to the Island dock where he is able to send a telegram to his connection to the outside world. We will call this connection the Hub. The Hub must determine the answer to this age old question, and return the information gained from this query to Sam.

Task 3: Get your clothes dry-cleaned (The dry-cleaners is not on the island).

This task is relatively simple for Sam, he simply takes your clothes and sends them to the Hub who will return them to Sam when they are done being cleaned.

Task 4: Retrieve a magical rock from the top of MountainJS on the Island.

Fortunately for Sam, MountainJS is located on the island, so he can take care of this task himself. Unfortunately however, MountainJS is a tall, treacherous mountain, where return is not certain.

Sam’s Strategy

In order to work efficiently, Sam has implemented a system for keeping track of what tasks to do, and in what order. This system also receives returned messages for Sam, from the Hub. Sam calls this system the LaunchPad. Upon finishing a task, Sam will check the LaunchPad to see what he has to accomplish next.

Times Up Let’s Do This

Sam begins by inputting all 4 of his tasks into the LaunchPad. Since he can accomplish the first task by himself, he simply executes the first task.

Upon completing the first task, Sam returns to the LaunchPad to see what he has to do next. Task 2, requires him to send a message to the Hub to find out What kind of Bear is Best. Upon sending the message to the Hub, Sam must now wait for an answer. In order to be effecient, Sam marks this task as completed, knowing that a response will be returned from the Hub at some later point in time. So in the meantime Sam continues on to Task 3.

Once again, Sam cannot take care of this task himself, and must send your clothes to the Hub, so that they can be brought to the dry-cleaners. Sam sends the clothes, and again marks the task completed, again knowing that he will receive the clothes in a clean state from the Hub.

Although Sam is worried about Task 4, he bravely begins his ascent onto MountainJS to retrieve the magical rock. After a journey filled with much danger and peril, Sam returns to you with the magical rock as you requested. Sam then accesses the LaunchPad to mark task 4 complete.

Upon finishing task 4, Sam sees that while he was climbing MountainJS, the Hub returned your cleaned clothes. Sam then acquires the clothes and brings them to you. Task 3 is now entirely completed.

Unfortunately the Hub has not yet determined and returned information on the Best Bear. At this point, Sam is now waiting idle. During this wait, you come up with another task for Sam: To water the plants in the Garden. Sam immediately gets to work to complete this task. After finishing this new task for you, Sam checks the LaunchPad.

Finally the Hub has returned the answer to the question “What kind of Bear is Best?”. Despite the common misconceptions, it is in fact the Black Bear. Sam returns to you with this knowledge and marks the Task as completed.

Sam continues this strategy of task execution until he goes to bed, and then starts the process over the next day.

Analogy Explained

Your Minion Sam

Sam is analogous to the Call Stack in the JavaScript runtime. This is the single-thread that can only execute one task, or piece of code at a time.

The Hub

The Hub is analogous to the various Web/Node API’s. These API’s are the secret sauce behind the magic of JavaScript’s efficiency and asynchronous execution. In the future we will see examples of this with various HTTP requests. These asynchronous tasks are run in the background either by the browser on the web, or by the C++ layer of NodeJS.

The LaunchPad

The LaunchPad is analogous to the Task Queue. It tells the JavaScript runtime which code to run after it has finished running the current block of code that it is running.

Some Other Awesome Resources

Here is an incredible talk given at the 2014 JSConf by Philip Roberts. This is the best resource that I personally have found regarding the JavaScript runtime and the Event Loop! Followed by several other links.

10/10 Can’t Recommend Enough!

https://nodesource.com/blog/understanding-the-nodejs-event-loop/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

Stay Tuned

Please join me in this series of Asynchronous Adventures where I will be highlighting how to handle asynchronous code in JavaScript from the basic stuff, to the advanced, fancy strategies.

This series covers in-depth analysis (with examples!) of the following JavaScript patterns:

Ben Diuguid is currently a student at the University of Florida. He is incredibly passionate about creating things, especially with JavaScript.

--

--