The Main Event… Loop
First, let’s take a look at what the runtime environment actually looks like.
As you can see the runtime consists of a stack and a heap. We don’t need to worry about the heap to talk about the event loop. Basically, it’s a bunch of memory that can be allocated as needed and referred to by the stack. What we are interested in is the stack itself.
Since the call stack is, well — a stack, we can only execute the last item pushed onto it.
So, what happens if that function takes a long time to execute? That’s called blocking. Blocking is when the execution of your code is held up or blocked by some process, and nothing else can happen until it completes.
If that’s the case, why doesn’t our entire program freeze every time we make an HTTP request? To understand this, we need to take one giant step back and look at the bigger picture.
- Third-party APIs (which are not built into the browser) include things like the Spotify API or the Watson APIs, where you make some sort of request through a server and receive a response.
The browser APIs are capable of executing their own code outside of the call stack. You can think of them as separate threads that your code can make calls to but not access directly.
What happens when something you started in a browser API completes? Say you executed a fetch and got a response - we don’t want the Fetch API pushing that response to the call stack whenever it randomly completes, or we could screw up the code that is currently running. We need something to hold onto all of those responses until the call stack is ready for them. That’s where the message queue comes in.
The Message Queue
The message queue is responsible for holding all of the messages that are generated from processes completed by browser APIs. As the call stack empties, the messages are executed (oldest first because it’s a queue) and their callback functions are added to the call stack. We’re still missing one vital piece of the puzzle. We need something to regulate the flow between the call stack and the message queue. That something is the Event Loop.
The Event Loop
The Event Loop is responsible for determining if the call stack is ready, and if it is, then executing the next message in the queue.
Cool, but what does that mean?
- If you want to learn more, this talk by Philip Roberts is a really great resource.