javascriptloopswhile-looptimingevent-loop

JavaScript: Why can't you update looping variable from external variable


I was playing around but I don't understand why this won't work? In theory, I thought it would but it just goes into an endless loop. Don't run it, it will most likely lock up your computer.

glb = "original";

async function wait() {
    await new Promise(resolve => setTimeout(resolve, 2000));
    glb = "updated";
}

function f() {
    wait();
    var glb2 = "original";
    while (glb2 == "original") {
        glb2 = glb;
        console.log("####  glb:" + glb);
    }
    console.log("#### DONE  glb:" + glb);
}

f();

Why does glb2 never get updated?

Thanks!


Solution

  • Well friend, this happens because the "await()" function returns a promise, which doesn't give time to update the variable to "updated". For that, you need to make the function "f()" as asynchronous also waiting for the execution of the function "await()" with the use of the reserved word "await", as follows:

    async function f() {
        await wait();
        // rest of the function...
    }
    

    That way you can avoid the infinite loop.

    Good luck.