Confused about some Async javascript code

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

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.

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.

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