sleep() in JavaScript
1 | function sleep(ms) { |
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:
- Promises, a native feature of ES2015 (aka ES6). We also use arrow functions in the definition of the sleep function.
- The
async
/await
feature lets the code explicitly wait for a promise to settle (resolve or reject).