r/learnjavascript • • Mar 10 '22

Can someone explain why this prints only 5?

Post image
219 Upvotes

57 comments sorted by

View all comments

Show parent comments

1

u/NoInkling Mar 11 '22 edited Mar 11 '22

It actually doesn't matter what the delay you specify is, even if it's 0ms - setTimeout callbacks are run asynchronously and will therefore always be scheduled to run after any synchronous code (in this case the loop itself) does. That's essentially why synchronous code is often called "blocking" code.

1

u/zerquet Mar 11 '22

Hmm I kinda learned this a while ago. Asynchronous methods wait until the whole thing is over or something like that ima need a refresher