Skip to content

How asynchronous JavaScript works under the hood

Daisho Komiyama edited this page Jul 25, 2019 · 12 revisions

Hi, Today, I watched an amazing tutorial video about JavaScript asynchronous feature and learned how it works under the hood.

Exercise 1

Write the order of 3 function executions

function printHello () {
    console.log('Hello');
}

function blockFor1Sec () {
    //assume looping on huge array and it takes approximately 1 second to complete
}

setTimeout(printHello, 0);

blockFor1Sec();

console.log('Me first!');

What happens under the hood

async analogy

Answer for exercise 1

  • blockFor1Sec (1ms - 1001ms)
  • 'Me first!' (1002ms)
  • 'Hello' (1003ms)

Explanation for exercise 1

When setTimout (Web browser feature) is used, the function in callback parameter position, in this case printHello, is pushed to Callback Queue and it won't be pushed to Call Stack until all global functions executed. So in this case, blockFor1Sec() and console.log('Me first!') are executed before printHello even setTimeout's timer was expired long ago.

Clone this wiki locally