0

I have a for loop with a setTimeout function inside of it intended to delay each iteration of the loop. While the rest of the code within the loop is properly iterating, the setTimeout function only works once, as if the for loop was inside of it and not the other way around. Here's my code:

    for (x = 0; x <= roll; x ++) {
        setTimeout(function() {
            space = $(".player." + turn).parents("td").attr("id");
            space = parseInt(space);
            player = $(".player." + turn);
            $(".player." + turn).remove();
            nextSpace = space + 1;
            $("#" + nextSpace).append(player);
        }, 500);
    }

Any ideas?

1
  • 1
    Those setTimeouts are going to be called in rapid succession without delay. You need to use a callback within the setTimeout to implement a delay. Commented Mar 10, 2013 at 7:40

2 Answers 2

4

Try this:

setTimeout(function() {
    // your code
}, 500 * x);
Sign up to request clarification or add additional context in comments.

Comments

1

This is not how setTimeout works. It is not a synchronous delay. If you want to delay each iteration of your loop, you need to instead do this by recursively calling the inner function.

function inner_function(x, max_x) {
    space = $(".player." + turn).parents("td").attr("id");
    space = parseInt(space);
    player = $(".player." + turn);
    $(".player." + turn).remove();
    nextSpace = space + 1;
    $("#" + nextSpace).append(player);

    setTimeout(inner_function, 500, x+1, max_x);
}

inner_function(0, 500);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.