DEV Community

Cover image for What is the JavaScript version of sleep()?
Grzegorz Kućmierz
Grzegorz Kućmierz

Posted on • Edited on

What is the JavaScript version of sleep()?

There is no sleep function in JavaScript, but with async/await syntax it is very easy to implement.

If we need to mimic behavior like this written in c code.

#include<stdio.h>

main() {
   printf("Sleeping for 1 second.\n");
   sleep(1);
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

Using async/await syntax it is very simple.

const sleep = (timeout = 1) => new Promise((resolve) => {
  setTimeout(resolve, timeout * 1e3);
});

console.log('before sleep');
await sleep(1);
console.log('after 1 second!');
Enter fullscreen mode Exit fullscreen mode

You can also use milliseconds version.

const sleepMs = (timeout = 1e3) => new Promise((resolve) => {
  setTimeout(resolve, timeout);
});

console.log('before sleep');
await sleep(1000);
console.log('after 1000 milliseconds!');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)