JavaScript如何优雅的实现Sleep
JavaScript 如何优雅的实现
sleep
sleep
想要暂停一小会儿, 又不想嵌套一堆 setTimeout
直接贴人家的代码:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two seconds later, showing sleep in a loop...');
// Sleep in loop
for (let i = 0; i < 5; i++) {
if (i === 3)
await sleep(2000);
console.log(i);
}
}
demo();
注意事项:
- 方法名需要加上:
async
关键词 - 方法内部需要以:
await sleep(2000)
方式调用
参考:
- What is the JavaScript version of sleep()?
- JavaScript Promise 对象
- js 箭头函数 lambda
- 理解 JavaScript 的 async/await
blog comments powered by Disqus