I am in need of a sleep function for my JavaScript code. I could use a promise-based function, but it requires the await
keyword to function correctly. The issue is that I need to use the sleep function at the top level of my code.
function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
await sleep(5) //invalid
Since JavaScript does not support await
at the top level, I'm unable to write await sleep(5)
.
Is there a way to implement a function that will perform like this?
let i = 10;
while (i > 0) {
console.log("sleeping..." + i);
sleep(1);
i--;
}
console.log("Hello");
sleep(5);
console.log("World");
Any suggestions on how to achieve this?