JavaScript里面没有sleep功能,只能曲线实现:
1、for循环:
function sleep(d){
for(var t = Date.now();Date.now() - t <= d;);
}
sleep(1000); //闯入毫秒,如1秒,传递1000
2、while循环:
function sleep(d){
var beginTime=new Date().getTime();
while(new Date().getTime() < beginTime + d) {}
}
sleep(1000); //闯入毫秒,如1秒,传递1000
3、async + await
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
await sleep(2000);
console.log('Two second later');
}
demo()