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

How to set a function to execute later in Javascript if it will take a long time?

function wait() {
    let a = Date.now()
    while (Date.now() - a < 3000) {
        //loop
    }
    console.log('waiting ends...')
}
function start(){
    console.log('starts...')
    wait()
}
function end(){
    console.log('ends...')
}

start()
end()

How can I set wait() execute asynchronously that lead to a output of "starts…, ends…, waiting ends…" without apply setTimeout function to wait()?

>Solution :

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

You can convert wait() to an async function an use await to postpone the rest of the function’s body:

async function wait() {
    await true;
    let a = Date.now()
    while (Date.now() - a < 3000) {
        //loop
    }
    console.log('waiting ends...')
}
function start(){
    console.log('starts...')
    wait();
}
function end(){
    console.log('ends...')
}

start()
end()

Or you can do it with start():

function wait() {
    let a = Date.now()
    while (Date.now() - a < 3000) {
        //loop
    }
    console.log('waiting ends...')
}
async function start(){
    await console.log('starts...')
    wait();
}
function end(){
    console.log('ends...')
}

start()
end()

You can use queueMicrotask() to execute a function as a microtask (the same as immediately resolving a promise):

function wait() {
    let a = Date.now()
    while (Date.now() - a < 3000) {
        //loop
    }
    console.log('waiting ends...')
}
function start(){
    console.log('starts...')
    queueMicrotask(wait);
}
function end(){
    console.log('ends...')
}

start()
end()
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