How Javascript Works: Asynchronous JS

Javascrpit is a single threaded, non-blocking, asynchronous language.

Why we say it is Single threaded?

Consider the code below:

1
2
3
4
5
6
7
8
9
function add(num1,num2){
let sum = num1 + num2;
function output(value){
console.log(value)
}
output(sum)
}

add(1,2);

It is gonna run on the stack that looks like:

The first called function will be pushed onto the bottom of the stack and the top function will be popped out and executed first.

Each function got executed in order, everything looks good, especially in the program tiny like this.

Single threaded means the JS engine only have one call stack and one memory heap( to store varibles ).

The problemt is: blocking

If you run this in your browser:

lang = Javascript
1
2
alert("help")
console.log("nice")

“Nice” will never show up, if you don’t click on the alert.
That is because the call stack is occupied by the alert() and the console.log() is waiting for the completion of the previous function.

Also, a blocking example is: a user will not see the whole web page untile the JS engine finish rendering, it must be frustrated.

Then how we can solve it? The answer is using asynchronous function.

Asynchronous

  1. Synchronous vs Asynchronous

Let’s first see how synchronous process works:

lang = Javascript
1
2
3
4
5
6
7
console.log("hi")
console.log("how can i help you?")
function giveBread(){....}
function giveBacon(){....}
....
console.log("bye")
serveNextCustomer()

This is a typical synchronous working flow. It works well and everything is predictable.

But imagine that we are in a restaurant, we want to order some food, maybe just a piece of bread. But the guy in front of us is ordering a lot, we have to wait.

The same issue happens in the synchronous working process: if a time-consuming function runs first, it may block user to interact with the appication while it’s loading.

  1. A type of async: callback function

Then let’s see a old-fashion way to accomplish async.

lang = Javascript
1
2
3
4
5
console.log(1)
setTimeOut(callback() =>{
console.log(2)
},2000)
console.log(3)

It is gonna show:

1
2
3
1
3
2

But why that happens? Why it is not 1 2 3?

Here goes the Javascript Run-Time Environment

The timeout function belongs to the WebAPI. It is not gonna run directly on the stack, it is on the background of the JS engine.
What the code does is, firstly console.log(1) runs. Then the setTimeOut(…) function is called and executed on the stack. The engine then notices this function is in Web APIs, so it saves both the timer and the callback() function in the browser’s thread and move out the setTimeOut(..) function from the stack. After the timer counting down and the time is up, the callback() function got pushed onto the Callback Queue.

The Event Loop kicks in, which is monitoring the callback queue all the time, to see when the stack is empty and push the first waiting callback onto the stack for executing.

In that way, the function is executed not in order. To sum up, the callback function is used to “do something after finish something rather than do it directly”.

Alright, that is it.

Reference

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing
https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-coding-with-2f077c4438b5