What's the JavaScript version of sleep
There’s no sleep function in JavaScript, how can we make one?
Let’s jump right in and write the function.
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
It’s a straight forward function that when called returns a Promise
that’s resolved after the given number of milliseconds.
How do we use this function?
// sleep for one second
sleep(1000).then(() => {
// do something!
});
Please that any code right after sleep
before the code inside the then
function.
We can also use async
/await
// sleep for one second
await sleep(1000);
// do something!
That’s it, a super quick way to create a sleep function in JavaScript.
Useful for when we, for example, want to sleep an authentication process a random number of milliseconds to obfuscate if our server is busy or not.