I need a sleep function for my Js code. I can use a promise based function but that needs await
keyword to work. But the problem is I need to use the sleep function at the top level.
function sleep(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
await sleep(5) //invalid
So I can’t write await sleep(5)
because Js do not support it.
How to implement a function that will work like,
let i = 10;
while (i > 0) {
console.log("sleeping..." + i);
sleep(1);
i--;
}
console.log("Hello");
sleep(5);
console.log("World");
Is there any way?
3
Answers
Though it’s crazy and not recomanded but Yes you can implement that with
Date.now()
function.This function compares the current time with the starting time using your defined time.
As we know
while loop
like this will block the main thread and the next lines are not executed until it releases the thread.Hope that helps.
I don’t think there is any way to do it without a level of wrapping, if you cannot use top level awaits.
You can use
.then
Another way to do this is using an IIFE.
Top-level await is supported in Ecmascript Modules. Since you’re using the Node.js, the easiest way to switch is to rename your
.js
file to.mjs
.If you can’t do that, your only other option is wrapping your code in a function.