Top level sleep function for Javascript

53 views Asked by At

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

There are 3 answers

2
Fuad Hasan On BEST ANSWER

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.

3
Tushar Shahi On

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

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

sleep(2000).then(() => {
  //Sadly all your logic will reside inside this block
});

Another way to do this is using an IIFE.

function sleep(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

(async () => {
  await sleep(3000);
  //Sadly all your logic will reside inside this block

})();
0
Evert On

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.