Confused about some Async javascript code

I’ve been learning about asynchronous code in Javascript and I was following this
article.

In the last code snippet, the main function firsts adds setTimeout(f1, 50) then setTimeout(f3, 30) to the task queue. What I thought was after all the synchronous code and the job queue is done, then after 50 ms then “f1” would be printed and finally after another 30 ms “f3” would be printed out. However, the result says “f3” then “f1”.

Can someone help explain why does this happen? Thanks.

You are correct, that is what happened. 50 ms takes longer than 30 ms, so the f3 shows up first and then the f1.

setTimeout executes the function after the specified delay. Since 30 milliseconds is faster than 50 milliseconds, f3 will be executed before f1. The setTimeouts start counting the delay immediately. The second one doesn’t wait for the first one to finish. That’s what makes then asynchronous.