JavaScript 中有睡眠功能吗?
JavaScript 中有睡眠功能吗?
IT技术
javascript
2021-02-05 18:21:55
4个回答
如果您希望通过调用来阻止代码的执行sleep,那么不,在JavaScript.
JavaScript确实有setTimeout方法。setTimeout将让您将函数的执行推迟x 毫秒。
setTimeout(myFunction, 3000);
// if you have defined a function named myFunction
// it will run after 3 seconds (3000 milliseconds)
请记住,这与sleep方法(如果存在)的行为方式完全不同。
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
如果您运行上述函数,您将必须等待 3 秒钟(sleep方法调用被阻塞)才能看到警报 'hi'。不幸的是sleep,在JavaScript.
function test2()
{
// defer the execution of anonymous function for
// 3 seconds and go to next line of code.
setTimeout(function(){
alert('hello');
}, 3000);
alert('hi');
}
如果您运行 test2,您将立即看到“hi”(setTimeout非阻塞),3 秒后您将看到警报“hello”。
一种简单的、CPU 密集型的方法来阻止执行数毫秒:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
您可以使用setTimeout或setInterval函数。
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
此代码在指定的持续时间内阻塞。这是 CPU 占用代码。这与线程阻塞自身并释放 CPU 周期以供另一个线程使用不同。这里不会发生这样的事情。不要使用此代码,这是一个非常糟糕的主意。
其它你可能感兴趣的问题