DEV Community

Discussion on: Where’s the Sleep Function in JavaScript?

Collapse
 
aumayeung profile image
John Au-Yeung

This only works if each iteration runs for a millisecond, doesn't it?

Collapse
 
karataev profile image
Eugene Karataev

Each iteration in the above code runs much faster than 1ms.
But it doesn't actually matters, because as Calin said this is an unaccepted way of implementing sleep function, because it blocks main thread and loads CPU at 100% for no profit.

Btw, setTimeout(fn, 2000) doesn't mean that fn will be called exactly after 2s. It'll be exectuted at least after 2000ms.