sleep() in JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()

This is it. await sleep(<duration>).

Or as a one-liner:

await new Promise(r => setTimeout(r, 2000))

Note

await can only be executed in functions prefixed with the async keyword, or at the top level of your script in some environments (e.g., the Chrome DevTools console, or Runkit).

await only pauses the current async function

Two new JavaScript features helped write this "sleep" function: