-3

is there a way to do a setTimout for each iteration of a loop?

I basically want each iteration at 500

setTimeout(function(), 500); }

If so, how would it look?

for (var i = 0; i < 10; i++){

}

Doc Holiday
  • 9,928
  • 32
  • 98
  • 151
  • 1
    What do you mean? You want to wait 500 ms for each iteration? – putvande Jun 24 '14 at 16:12
  • You mean you want things to happen with a 500 ms delay between them? Yes, there is but your code will be asynchronous, you'll have to be notified that your loop is finished with callback – Ruan Mendes Jun 24 '14 at 16:12
  • 2
    possible duplicate of [How do I add a delay in a JavaScript loop?](http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Adam Jun 24 '14 at 16:13
  • You could do `setTimeout` in a loop, but then you would just be causing `i` functions to execute at the same time. Is this really what you want? – nullability Jun 24 '14 at 16:14
  • yes thats what I want – Doc Holiday Jun 24 '14 at 16:20

2 Answers2

0

So you have a piece of code that you want to execute N number of times, waiting 500ms between each execution?

You could use setInterval (https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval) instead of setTimeout, and then within the code you're executing on the interval, include a counter and a condition to remove the interval (Stop setInterval call in JavaScript) after the correct number of executions.

Community
  • 1
  • 1
stranger
  • 390
  • 4
  • 17
0

You can't do this type of stuff in a for loop. But you can emulate it:

var latency = 500,
    iteration = 0,
    numIterations = 10;

var loop = function() {

    // Do your stuff, like:
    console.log( iteration );

    /*
    // break; simulation - return early if some condition was achieved:
    if ( iteration == 8 ) {
        return;
    }
    */

    // Loop handling, you'll need those lines, don't remove.
    iteration += 1;
    if ( iteration < numIterations ) {
        setTimeout( loop, latency );
    }
}

loop(); // invoke first cycle
Ingmars
  • 998
  • 5
  • 10