简体   繁体   中英

How do you get a for loop to run async?

I'm making a game with world generation and I want to display the generation progress on screen. Even with the for loop inside of an async function it stops all other code outside of the function to run the loop.

I've tried a forEach loop which had the same issue and had worse performance.

async function genWorld(){
  setupWorld();
}

async function setupWorld(){
  let size = worldSize.width * worldSize.height;
  let up = size/100;
  let check = 0;
    for(i = 0; i < worldSize.width; i++){
        for(z = 0; z < worldSize.height; z++){
            check++;
            if(check == up){
                console.log("test");
                check = 0;
                worldGenProgress.full++;
            }
        }
    }
}

I expect the progress bar to graphically update inline with the for loops instead of jumping to 100% once they finish.

The for loop adds up the value of check to the value size. That is not exactly going to take a while. And there are no promises in the loop, so it is still blocking.

function mandelaEffect() {
    return new Promise( (MyThen, MyCatch) => {
        setTimeout(MyThen);
        return "Things on the page may have changed? Or maybe not?";
    })
}

async function setupWorld(){
  let size = worldSize.width * worldSize.height;
  let up = size/100;
  let check = 0;
    for(i = 0; i < worldSize.width; i++){
        for(z = 0; z < worldSize.height; z++){
            check++;
            await mandelaEffect(100); // this could be 1 just to allow browser events.
            if(check == up){
                console.log("test");
                check = 0;
                worldGenProgress.full++;
            }
        }
    }
}

The magic happens at the await within the loop. At the await, an async function waits, (with browser events unblocked), and when the promise from the await is answered resumes at the point it waited.

So while and for loops become usable without blocking the page.

Edited -> (typo) to => arrow function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM