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!');
Top comments (0)