Skip to content

Implement sleep

Daisho Komiyama edited this page Feb 22, 2022 · 2 revisions

Imagine, you have to write a function that artificially pauses function execution. Call it sleep.

// definition
function sleep(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

// 1. using then
sleep(2000).then(() => console.log('done!'))
// done! (after 2sec)

sleep(5000).then(() => console.log('super long!'))
// super long! (after 5sec)

// ======================================

// 2. using await
async function run() {
  console.log("start");
  await sleep(2000);
  console.log("hello");
  await sleep(2000);
  console.log("world");
}

run()
Clone this wiki locally