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.
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.
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:
I've tried with setTimeout delay of 0, which I expected to run before
third
.but I was surprised to see that
second
was returned last.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.
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.
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...
Thank you, Oscar 🤜