Answer from stackoverflow
https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
I think it's perfectly reasonable to want to perform an action, wait, then perform another action. If you are used to writing in multi-threaded languages, you probably have the idea of yielding execution for a set amount of time until your thread wakes up.
The issue here is that JavaScript is a single-thread event-based model. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. Suppose I wanted to make use of your functions while writing my own? When I called your method, my methods would all freeze up. If JavaScript could somehow preserve your function's execution context, store it somewhere, then bring it back and continue later, then sleep could happen, but that would basically be threading.
So you are pretty much stuck with what others have suggested -- you'll need to break your code up into multiple functions.
Your question is a bit of a false choice, then. There is no way to sleep in the way you want, nor should you pursue the solution you suggest.