How Does Asynchronous Javascript Work?

A seriously necessary question which any JS programmer should be able to easily explain. Let’s make it simple:

Syncronous code is the code which runs each instruction in order, one by one. Let’s take a simple example:

const two= () => {
  console.log(2);
}

const go = () => {
  console.log(1);
  two();
  console.log(3);
}

go();

And the result, as expected because everything gets output in the same order as it is written in the code.

1
2
3

Cool. Nothing weird here.

Now let’s make it asynchronous.
Asynchronous Javascript will have some code which is executed later, out of the order in which is called in the code. The easiest way to show this is with the setTimeout function.

const two = () => {
  setTimeout(() => {
    console.log(2);
  }, 1000);
};

const go = () => {
  console.log(1);
  two();
  console.log(3);
};

go();

I have added the setTimeout function and made it run in the the two() function with a delay of 1000ms (1 second). Now let’s look at the output:

1
3
2 //with a delay of 1 second

Ok so what happened here?
Did you expect that the console.log(3) will wait until the timer ran out and executed after that? No, that’s not how it works.
To keep it short and simple, this is what happened:

  1. We called the go function.
  2. “1” got printed
  3. the two() function was called and it started the 1 second timer in the background
  4. Starting the timer did not prevent the execution from continuing and we moved on and printed “3”
  5. the 1 second timer ran out and and the two() function printed 2.

Ok. That is a super simple explanation of how asynchronous javascript functions. To get into more details, see my next post about what happens in the event loop when we run asynchronous code.

Leave a Reply