Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Top level sleep function for Javascript

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading