async function sleep(time) {
await new Promise((resolve,reject)=>{
setTimeout(() => {
// console.log(`等了${time}s`)
resolve()
}, time)
})
}
async function doSome(params) {
for (let x = 0 x < array.length x++) {
const eleArr = array[x]
for (let y = 0 y < eleArr.length y++) {
const ele = eleArr[y]
console.log(ele.level)
await sleep(ele.time)
if (x>=array.length-1 && y>=eleArr.length-1) {
doSome()
}
}
}
}
doSome()
1. jquery的$.delay()方法设置一个延时来推迟执行队列中之后的项目。这个方法不能取代JS原生的setTimeout。
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it 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
}