Member-only story

JavaScript Interview Questions

The Execution Order of Asynchronous Functions in the Event Loop

--

Interview Question

What is the output of the following code?

Analysis

This question is actually examining the execution order of the code. To be precise, it is examining the difference between asynchronous functions such as setTimeout, Promise, and async/await.

Let’s look at the simplest case first:

console.log('111')console.log('222')

What is the execution result of this code? Anyone who has studied programming knows that the program will output 111 and 222 in sequence. There is no asynchronous code in this code, so it is very simple.

Let’s look at another example:

console.log('111')setTimeout(() => {
console.log('333')
}, 0)
console.log('222')

What is the output of the above code?

In this code, we added an asynchronous function setTimeout. We can draw a diagram to show the execution flow of the code.

We know that there is a task queue in JavaScript, and all asynchronous callback functions will be put into this task queue first, and then executed when the main thread is free.

In the code above:

  • console.log(‘111’) will be executed first, so the console will print 111
  • Then execute setTimeout(..., 0). Note that in this step, the JS engine executes only the function setTimeout, and its callback function will not be executed. Then setTimeout will create a timer, the time of this timer is 0, so its callback function will be immediately pushed into the task queue

--

--

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.

Responses (3)

Write a response