JavaScript中有睡眠功能吗?

JavaScript中有睡眠功能吗?



慕容708150
浏览 1622回答 3
3回答

汪汪一只猫

您可以使用setTimeout或setInterval功能。

慕容3067478

如果您希望通过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”。

当年话下

一种幼稚的,占用大量CPU资源的方法,可在几毫秒内阻止执行:/*** Delay for a number of milliseconds*/function sleep(delay) {&nbsp; &nbsp; var start = new Date().getTime();&nbsp; &nbsp; while (new Date().getTime() < start + delay);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript