Sol*_*ogi 306
如果你想通过调用来阻止代码的执行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)
Run Code Online (Sandbox Code Playgroud)
请记住,这与sleep方法(如果存在)的行为方式完全不同.
function test1()
{
// let's say JavaScript did have a sleep function..
// sleep for 3 seconds
sleep(3000);
alert('hi');
}
Run Code Online (Sandbox Code Playgroud)
如果运行上述功能,sleep则在看到警报"hi"之前,您必须等待3秒钟(方法调用阻止).不幸的是,没有这样的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');
}
Run Code Online (Sandbox Code Playgroud)
如果你运行test2,你会立即看到'hi'(setTimeout非阻塞),3秒后你会看到警告'hello'.
And*_*eda 82
您可以使用setTimeout或setInterval功能.
小智 77
如果运行上述功能,则必须等待3秒钟(睡眠方法调用阻塞)
/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Run Code Online (Sandbox Code Playgroud)
Sha*_*lab 44
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Run Code Online (Sandbox Code Playgroud)
此代码阻止指定的持续时间.这是CPU占用代码.这不同于线程阻塞自身并释放CPU周期以供另一个线程使用.这里没有这样的事情发生.不要使用这段代码,这是一个非常糟糕的主意.