1

I have a for loop like so:

for(int i=0; i < 10; i++) {
    MyFunc(i);
}

How would I have the program run every 3 seconds so the program would run MyFunc(0) ..wait 3 sec.. MyFunc(1) ..wait 3 sec.. etc?

Bijan
  • 7,737
  • 18
  • 89
  • 149

1 Answers1

0

You need to set a different delay for each iteration:

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

function runIt(i) {
    setTimeout(function(){ 
       MyFunc(i);
    }, i * 3000);
}

See it in action here:

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

function runIt(i) {
    setTimeout(function(){ 
      //MyFunc(i);
      document.body.innerHTML = i;
    }, i * 3000);
}
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • 1
    While this works, it's worth to point out that this is probably not scalable. There are only so many timeouts you should have... – Felix Kling Dec 18 '14 at 23:30