JS中怎么实现sleep(休眠)的功能

JS中如何实现sleep(休眠)的功能?

<!--[if gte mso 9]><xml><w:WordDocument><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery><w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery><w:DocumentKind>DocumentNotSpecified</w:DocumentKind><w:DrawingGridVerticalSpacing>7.8</w:DrawingGridVerticalSpacing><w:View>Normal</w:View><w:Compatibility></w:Compatibility><w:Zoom>0</w:Zoom></w:WordDocument></xml><![endif]-->

1. jquery$.delay()方法

设置一个延时来推迟执行队列中之后的项目。这个方法不能取代JS原生的setTimeout。

The .delay() method is best for delaying between queued jQuery effects. Because it is limitedit doesn't, for example, offer a way to cancel the delay.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

例子:.slideUp() 和 .fadeIn()之间延时800毫秒。

HTML 代码:

<div id="foo /">

jQuery 代码:

$('#foo').slideUp(300).delay(800).fadeIn(400);

2. 通过循环消耗cpu

    function sleep(n) {

    var start = new Date().getTime();

    while(true)  if(new Date().getTime()-start > n) break;

    }

3. setTimeout

假设有三个步骤,步骤之间需要暂停一段时间;可以采用如下的方法:

function firstStep() {

//do something

setTimeout("secondStep()", 1000);

}

function secondStep() {

//do something

setTimeout("thirdStep()", 1000);

}

function thirdStep() {

//do something

}