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);
}
添加回答
舉報