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.
本文探讨了JavaScript中实现延时功能的局限性,解释了为何直接模仿多线程语言中的sleep方法不可行,并提出了将代码拆分为多个函数作为替代方案。进一步指出,直接使用sleep功能可能导致程序冻结,强调了在JavaScript单线程事件驱动模型下合理组织代码的重要性。
1288

被折叠的 条评论
为什么被折叠?



