且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JavaScript中,Java的Thread.sleep()相当于什么?

更新时间:2023-10-30 12:11:28

简单的答案是没有这样的功能。

The simple answer is that there is no such function.

你最接近的是:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

请注意,尤其不想忙等待(例如在一个旋转循环中),因为你的浏览器几乎肯定会在单线程环境中执行你的JavaScript。

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

这里有一些其他的SO问题来处理线程JavaScript:

Here are a couple of other SO questions that deal with threads in JavaScript:

  • JavaScript and Threads
  • Why doesn't JavaScript support multithreading?

这个问题也许有用:

  • setTimeout - how to avoid using string for callback?