Link to home
Create AccountLog in
Avatar of MJ
MJFlag for United States of America

asked on

JavaScript: Bastardization of for loop usage question

I don't understand why these don't theoretically work? First code block goes into an infinite loop while the second code block never outputs anything?  Please don't run these, your computer may lock up!


window.outSideVar = false;

async function wait() {
    await new Promise(resolve => setTimeout(resolve, 500));
    window.outSideVar = true;
    console.log("#### window.outSideVar updated in Promise: " + window.outSideVar);
}

function main() {
    wait();
    for (; window.outSideVar == false;) {
        console.log("#### <==> outSideVar : " + window.outSideVar);
    }
    console.log("#### DONE");
}

main();

Open in new window


Or something like this masterpiece that never even runs?

window.outSideVar = false;

async function wait() {
    await new Promise(resolve => setTimeout(resolve, 1000));
    window.outSideVar = true;
    console.log("#### window.outSideVar updated in Promise: " + window.outSideVar);
}

function main() {
    wait();
   for(let runIt = false; runIt == false; runIt = window.outSideVar){
        console.log("#### <==> runIt : " + runIt + " <==> outSideVar : " + window.outSideVar);
    } 
    console.log("#### DONE");
}

main();

Open in new window

Thanks!


ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer