Confusion reagrding Asynchronous function

I have a code

let a = 1
let b = 2
console.clear()
console.time('timer')


setTimeout(function(){
  console.log('Asynchronous')
},1)

for( let i = 0 ; i<100000 ;i++){
  let c = i+1;
}

console.log('Synchronous')
console.log(a);
console.log(b);
console.timeEnd('timer');

and the output is

Console was cleared
Synchronous
1
2
timer: 39.67578125 ms
Asynchronous

Now my question is that setTimeout function should take only 10ms where that for loop takes more than 10 ms (most probably 39 ms) then why Asynchronous print at the bottom instead of at the beginning?

why Asynchronous print at the bottom instead of at the beginning?

At a very high level, the timeout function gets pushed into a new stack.
the event loop continue with the functions it had in the stack and will run them till completion, before moving on to the next event loop.

Meaning that it will complete the loop and the console.log calls before moving on with the timeout function.

(which btw has a delay of 1ms and not 10ms as you say in your post)


As an anecdote back in the days you would see a lot of timeout function with a 0ms of delay like:

setTimeout(fn, 0)

This was done as a “hack” to force the browser to run the code after the current paint was done.
So in the days of jQuery where there were no reactive system, was a common trick to make sure the given code runs after the DOM/Browser has done updating :wink:

Hope this helps :sparkles:

1 Like

got more clear understanding after reading this The Execution Order of Asynchronous Functions in the Event Loop | by bytefish | Medium

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.