javascript有sleep方法么?

function test1()
{

   //some code

   //Let's say JS did have a sleep function.
   sleep(3000); //sleep for 3 seconds, 

   alert('hi');
}

非常不幸, 没有这个方法. 往往我们希望这样来做.

我们可以使用setTimeout(myFunction, 3000);  3000 为毫秒.  myFunction是我们要执行的方法.  这个方法的意思为, 延迟执行myFunction 3秒钟。 可以变相的实现我们想要的sleep。

function test2()
{
    setTimeout(function() { alert('hello');}, 3000);
//defer the execution of anonymous function for 3 seconds and go to next line of code. 

    alert('hi');
}

 

党我们执行test2 时, 会立即看到hi 的alert窗口。 三秒后,会看到hello的alert窗口。

另外, 搜索看到有的同学问 如下方法是否可以呢?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
  }

切忌, 千万不要使用。 这就是死循环,并没有释放cpu资源,并没有将该线程阻塞。 所以不要使用。

此篇文章已被阅读2936 次

Add a Comment

邮箱地址不会被公开。 必填项已用*标注