30秒学会 JavaScript 片段 · 2018年10月9日

30秒学会 JavaScript 片段 – sleep

Delays the execution of an asynchronous function.

Delay executing part of an async function, by putting it to sleep, returning a Promise.

代码片段

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

使用样例

async function sleepyWork() {
  console.log("I'm going to sleep for 1 second.");
  await sleep(1000);
  console.log('I woke up after 1 second.');
}