3 回答

TA贡献1773条经验 获得超3个赞
如果您希望通过to来阻止代码的执行sleep,那么不会,in中没有用于该方法的方法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”。

TA贡献1890条经验 获得超9个赞
一种幼稚的,占用大量CPU资源的方法,可在几毫秒内阻止执行:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
添加回答
举报