DEV Community

loading...
Cover image for What is the JavaScript version of sleep()?

What is the JavaScript version of sleep()?

Grzegorz Kućmierz
"Tell Me and I Forget; Teach Me and I May Remember; Involve Me and I Learn"
Updated on ・1 min read

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;
}

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!');

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!');

Discussion (0)

Forem Open with the Forem app