Asynchronous JavaScript & Event Loop
In this article, I explain how the call stack, event loop, call back queue, micro stack queue and more work together.
JavaScript is asynchronous and single-threaded. This means that it has only one Call stack and as such can run only one operation at a time. The Call stack is present in the JavaScript engine and executes any piece of code inside it.
Just consider sending a delayed API call, either as a result of a sluggish connection or because the server needs more time to respond. Generally, we are aware that the JavaScript interpreter lines-by-lines builds and runs code.
So, will JavaScript continue to wait for the API call to resolve? Without a doubt, the answer is no.
Therefore in order to perform operations such as network access without blocking the main thread, JavaScript provides us with an amazing tool kit of methods such as callbacks, promises, and async/await. But before we briefly go through those, let us analyze a few examples that will help us to better understand how asynchronous JavaScript and the event loop.
Suppose we have to execute this piece of code
function greet() {
console.log('Hi, I am Ekep');
}
greet();
console.log('You are a great Developer !');Whenever a piece of code first starts executing, the Call Stack is empty. A Global Execution Context (which represents the global scope ) of the code is created. This GEC which contains the code that is currently running, and everything that helps in its execution is pushed into the call stack for the interpretation and execution.
In this Global execution context, the whole code will be executed line by line. So as we move onto the first line, greet() will be allocated memory and stored. When greet() is called / invoked, an execution context for this function is created and pushed into the call stack. The function logs the message to the console and the its execution context gets deleted. The last message is logged to the console and the GEC is popped off the call stack.
The order of execution is:
>Hi, I am Ekep
>You are a great Developer !Click here to visualize a simulation of how this code compiles.
But what if we want our program to run after 5 seconds? The call stack cannot solely do this because it does not have a timer. The JavaScript engine makes use of Web APIs such as setTimeout(), DOM APIs, fetch(), Local Storage, console, and location. With this in mind, let us check out a few more examples:
console.log('Hi');
setTimeout(function greet(){
console.log('Sorry for the delay')
}, 5000);
console.log('Bye!');Once more, a GEC is created and added to the call stack. The code is then compiled line by line and executed by the interpreter. The message is logged onto the console by the JavaScript engine using the console Web API. The JavaScript engine uses the setTimeout to register the callback function passed to it and start the timer. The callback is kept in the Web API environment. The message is logged to the console when the final line is performed and the GEC is popped off of the call stack since there is no longer any code to compile.
When, 5000 milliseconds elapse, the greet() function needs to somehow be pushed into the call stack for execution. That is where the Callback Queue and the Event Loop come into play.
Callback Queue
The Callback Queue also called Task Queue is a FIFO (First In First Out) queue of Tasks that are going to be executed by the Event Loop. Tasks are synchronous blocks of code that can enqueue other Tasks while they’re running.
The difference between the Call Stack and the Callback Queue is that the Call Stack keeps track of the functions that are executed immediately, while the Callback Queue keeps track of functions that are going to be executed in the future.
The Task Queue is a FIFO queue of Tasks that are processed by the Event Loop. Tasks are synchronous blocks of code.
The Event Loop
The Event Loop works by continuously looping through the Task Queue and processing the Tasks it contains one by one. A single iteration of the Event Loop is called: a tick.
To process a Task, the Event Loop invokes the Function associated with it. While a Task is running, it has exclusive access to the Call Stack. The Event Loop waits to process the next Task until the current Task is finished, and the Call Stack is empty.
The greet() function is passed to the Call Stack through the Callback queue. Then the event loop serves as a gatekeeper to check the Callback queue and push anything into the call stack.
The order of execution is:
>Hi
>Sorry for the delay
>Bye!Click here to visualize a simulation of how this code compiles.
Let’s checkout this last example, where we are fetching data from an API
console.log('Start');
setTimeout(()=>{
console.log('Movie Pending...');
}, 5000);
fetch('https://api.themoviedb.org/3/77acd801b597c4084ac360528aebf8aa')
.then(()=>{
console.log('Movie');
});
console.log('End');We already know that when the code is run, a GEC is created. The GEC is then pushed into the call stack where it is compiled and executed line by line. The first line logs its message on the console, and the setTimeout registers its callback in the web browser’s environment and starts the timer. The fetch API of the browser sets its callback function which is called the “Microtask queue”. The last message is logged on the console.
You’re surely asking yourself which of the callbacks is pushed in the call stack first. Let’s first discuss a little about the microtask queue mentioned above.
Microtask Queue
The Microtask Queue was added in ES6 to handle Promises. It’s a lot like the Call Stack. The main difference is how Microtasks are enqueued and when they are processed.
Get Bessong Arrey-Etta’s stories in your inbox
Join Medium for free to get updates from this writer.
The Microtask Queue is a FIFO queue of Microtasks that are processed by the Event Loop. The Microtask Queue is very similar to the Task Queue. It was added to JavaScript’s execution model as part of ES6 in order to handle Promise resolution callbacks.
Microtasks are a lot like Tasks. They are synchronous blocks of code that have exclusive access to the Call Stack while running(Higher Priority than the Callback Queue)
The only difference between Microtasks and Tasks is where they are stored, and when they are processed.
- Tasks are stored in Task Queues. But Microtasks are stored in the Microtask Queue (there’s only one of these).
- Tasks are processed in a loop, and rendering is performed in-between Tasks. But the Microtask Queue is emptied out after a Task completes, and before re-rendering occurs.
So, the promise call back returned by the fetch function is pushed into the microtask queue first. The event loop constantly checks if the code in the call stack has finished executing so that it can push the code in this code into the Call Stack. When this is done, the code is executed and popped out of the call stack.
The order of execution is
>Start
>End
>Movie
>Movie Pending...Click here to visualize a simulation of how this code compiles.
For the last section of this article, let’s go through methods that will permit us to write non-blocking code.
Callbacks
A callback is a function passed to another function as a parameter and is called inside it,
function greet(callMeBack) {
callMeBack();
}Why do we need Call backs?
JavaScript runs code sequentially from top to bottom. However, there are some cases where we do not want our code to run sequentially, and we might want it to run after sometime or after an event is triggered/ a task is completed.
Here are a few examples of Callbacks;
setTimeout(function message(){
console.log('Have a wonderful day!')
}, 5000);
// Using arrow functions
setTimeout(() => {
console.log('Have a wonderful day!')
})
//Javascript is an event driven language.
//Event handlers are call backs
document.getElementById('btn')
.addEventListener('click', clickHandler)Promise
In JavaScript, a promise is a good way to handle asynchronous operations. It is used to find out if the asynchronous operation is successfully completed or not. A promise may have one of three states.
● Pending ● Fulfilled ● Rejected
Create a Promise
To create a promise object, we use the Promise() constructor.
let promise = new Promise(function(resolve, reject){
//do something
});The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and reject(). If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called.
Here is an example of a promise
const count = true;
let countValue = new Promise(function (resolve, reject) {
if (count) {
resolve("There is a count value.");
} else {
reject("There is no count value");
}
});
console.log(countValue);
output
>Promise {<resolved>: "There is a count value."}async/await
We use the async keyword with a function to represent that the function is an asynchronous function. The async function returns a promise.
The syntax of async function is:
async function name(parameter1, parameter2, …paramaterN) {
// statements
}The await key word is used inside an asynchronous function to await an asynchronous operation
// a promise
let promise = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve('Promise resolved')}, 7000);
});
// async function
async function asyncFunc() {
// wait until the promise resolves
let result = await promise;
console.log(result);
console.log('hello');
}
// calling the async function
asyncFunc();
Output:
>Promise resolved
>helloConclusion
So we have learned how asynchronous JavaScript works alongside other concepts like call stack, event loop, call back queue, micro stack queue which together, make the JavaScript runtime environment. We also briefly went through callbacks, promises and async/await.
There you have it! If you found this article helpful, please click the clap 👏button, you can also follow me on Medium and Twitter, and if you have any doubt, feel free to comment! I’d be happy to help :)







