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();

注意事项:

  1. 方法名需要加上: async 关键词
  2. 方法内部需要以: await sleep(2000) 方式调用

参考:



blog comments powered by Disqus

Published

24 April 2020

Tags