JavaScript中有睡眠函数吗?


您可以使用setTimeout或setInterval函数。


如果你想通过调用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)

记住,这和睡眠方法完全不同,如果它存在的话。

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

如果你运行上面的函数,你将不得不等待3秒(sleep方法调用被阻塞)才能看到警报'hi'。不幸的是,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);
}

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

该代码在指定的持续时间内阻塞。这是CPU占用代码。这与线程阻塞自身并释放CPU周期以供另一个线程使用不同。这里没有这样的事。不要使用这个代码,这是一个非常糟糕的主意。