AlwaysNeedingHelp
AlwaysNeedingHelp

Reputation: 1945

Waiting until for loop iteration to be completed visually before going onto next one

function start_map_one() {

for (var i = 0; i < 15; ++i) {
      $.when(update_map()).then(evolve('W','W1',18,2,sea_limitations,20,350));
}
}

here, update_map() updates a div. However instead of the div updating visually 15 times in sequence, it appears to wait until all 15 iterations are complete and then display the finished div.

So im looking for this order ideally:

update_map() map information is used to update the div - user sees the visual result... then...

evolve() map information updated behind the scenes

update_map() map information is used to update the div - user sees the visual result... then...

evolve() map information updated behind the scenes

etc etc 15 times

Upvotes: 0

Views: 717

Answers (2)

Anthony Chu
Anthony Chu

Reputation: 37520

Consider using recursion for this. Without knowing too much about what the code does, it could look something like this...

function start_map_one() {
    start_map_one_helper(15);
}

function start_map_one_helper(count) {
    if (count <= 0) {
        return;
    }
    $.when(update_map()).then(function () {
        evolve('W','W1',18,2,sea_limitations,20,350);
        start_map_one_helper(count - 1);
    });
}

Note that the then() callback needs to be wrapped in a function, otherwise it executes right away.

You may need to wrap the recursive call in a setTimeout to see the changes on the screen...

function start_map_one() {
    start_map_one_helper(15);
}

function start_map_one_helper(count) {
    if (count <= 0) {
        return;
    }
    $.when(update_map()).then(function () {
        evolve('W','W1',18,2,sea_limitations,20,350);
        setTimeout(function() {
            start_map_one_helper(count - 1);
        });
    });
}

Upvotes: 2

Steven
Steven

Reputation: 271

It's because you don't give the browser enough time to change the display. Just add a delay in between the execution of each iteration. Try this solution

function start_map_one() {
    for (var i = 0; i < 15; ++i) {
        setTimeout(function() {
            $.when(update_map()).then(evolve('W','W1',18,2,sea_limitations,20,350));
        }, i * 100);
    }
}

Change the 100 to a time suitable for you.

Also, you're not encapsulating the evolve function (Which means you're calling evolve during the loop instead of calling it through then. Simply wrap it in a function.

Upvotes: 0

Related Questions