You learned that web APIs are what actually process async operations while keeping the call stack clear of blocking operations. When a web API is done processing an async task, it’s not immediately executed on the call stack. Instead, its associated callback function gets pushed into something called the callback queue, which is a list (or line) containing all the async task callbacks waiting to be executed.

How the Callback Queue Works

You can think of the callback queue as a holding area for all the callbacks that are waiting to be put on the call stack and eventually executed. Only callbacks for (non-blocking) operations that are scheduled to complete execution at a later time like setTimeoutsetInterval and AJAX requests, for example, are added to the callback queue:

The web APIs add each async task to the callback queue where they wait to be pushed onto the call stack and executed one at a time.

Consider the same set of functions from the previous step:

function func3() {
  console.log('Students!');
}

function func2() {
  console.log('Treehouse');
}

function func1() {
  console.log('Hi');
  setTimeout(func2, 1000)
  func3();
}

func1();

// Hi
// Students!
// Treehouse

The image below demonstrates how the setTimeout callback function (func2) gets handed to off a web API, followed by the callback queue, then executed on the call stack.

After the 1000ms delay is up, func2 moves to the callback queue where it waits to be pushed onto the call stack.

So, where does the event loop come in, and why is it important?

The Event Loop

The event loop has one important job: monitor the call stack and callback queue. Anytime the call stack is empty, the event loop takes the first task from the callback queue and pushes it onto the call stack, and runs it. For example:

In the above sequence, the web APIs push async tasks (or callbacks) into the callback queue when they’re ready to be executed. Notice how the event loop pushes each onto the call stack one at a time. The following sequence demonstrates how the event loop manages the setTimeout() in the set of example functions shown above:

And that’s how the call stack, callback queue and event loop work together to manage and execute asynchronous tasks! Don’t worry about knowing every detail, but understanding the basics of the event loop and the execution order of the call stack is going to help you better manage and understand the flow of your programs. Be sure to review the resources below for more resources and examples of each.