It's time to tackle one of the most important concepts in JavaScript and one of the things that separates JS from most other coding languages. That's right — we're going to talk about the Event Loop and the JavaScript Runtime.

TLDR

If you want a quick reference for visualizing the "event loop" and what the heck it means, watch this video. It's the best explanation known to man, and takes less than 10 minutes to get through!

https://www.youtube.com/watch?v=8aGhZQkoFbQ

JavaScript Runtime Environment

The JS Runtime Environment consists of many things as shown below in the diagram. Let's take a minute to briefly go over each aspect of the environment as it'll become very important when we start talking about "Async" in JavaScript.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d89461da-4c45-4dd1-a61a-2620268f4e97/Untitled.png

  1. V8 JavaScript Engine
  2. The Web API Container
  3. Callback Queue
  4. Event Loop

Call Stack Examples

Now that we have described the JavaScript Runtime Environment, let's dive into a quick example to illustrate how the call stack works.

I've gone ahead and written some trivial code below and using a super cool tool called loupe we can visualize what the call stack looks like as the code is executed. Play this video a couple times until you feel comfortable with how the call stack works.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/3ddfe862-f99b-4739-a80c-45c9c7efa4db/Screen_Recording_2019-10-02_at_10.18.38_PM.mov

Blocking vs Non-Blocking I/O

Now that you have a good understanding of the call stack, consider what would happen if the following function was pushed onto the call stack.

function yourWorstNightmare() {
	while true {
		// insert scary music
	}
}

Because this function is an infinite loop, it would never finish and always remain on the top of the call stack. This would effectively stop your JS program and "block" the next function from ever being executed. When we refer to "blocking function" what we mean is a function that takes a long time to execute and will prevent other functions from running while the blocking function hogs the call stack. Blocking functions are typically things like network requests, file reading/writing, image processing, timers, etc.

Synchronous vs Asynchronous