DEV Community

Discussion on: If Javascript Is Single Threaded, How Is It Asynchronous?

Collapse
 
dance2die profile image
Sung M. Kim

I've tried with setTimeout delay of 0, which I expected to run before third.

console.log("first")
setTimeout(() => {
    console.log("second")
}, 0)
console.log("third")
first
third
undefined
second
Enter fullscreen mode Exit fullscreen mode

but I was surprised to see that second was returned last.

Collapse
 
realtimecarsten profile image
realtimecarsten

In most operating systems, the wait or sleep functions are lower bounds - wait(n) will wait for at least n time-units, but once the time is up, you will never know when your tasked is scheduled next - sometimes that can be really long.

Collapse
 
elijahtrillionz profile image
Elijah Trillionz

It's an interesting thing about it.
No matter the delay it will always come after the call stack is empty.
Try using this website loupe to see more of it.

Collapse
 
owl profile image
Oscar • Edited

The function in your timeout gets queued as a task. The script runs and once it is done (console.log('third')), the engine can handle the task queue and will execute the timeout callback. So, even though the timeout is zero, the function will not get called immediately.

There is a lot more to the topic and Jake Archibald wrote an amazing article about how this works. I highly recommend reading it:

jakearchibald.com/2015/tasks-micro...

Collapse
 
dance2die profile image
Sung M. Kim

Thank you, Oscar 🤜