JavaScript 中有睡眠函数吗?
2022-08-30 00:28:57
JavaScript 中有睡眠函数吗?
如果您希望通过调用 来阻止代码的执行,那么不,在 中没有方法可以做到这一点。sleep
JavaScript
JavaScript
确实有方法。 将允许您将函数的执行延迟 x 毫秒。setTimeout
setTimeout
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 秒钟(方法调用被阻止)才能看到警报“hi”。遗憾的是,在 中没有这样的功能。sleep
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”(未阻塞),3秒后您将看到警报“hello”。setTimeout
一种朴素的 CPU 密集型方法,可阻止执行数毫秒:
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}