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?
Though it's crazy and not recomanded but Yes you can implement that with Date.now()
function.
function sleep(seconds) {
const start = Date.now();
while (Date.now() - start < seconds * 1000) {}
}
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.