Search code examples
javascriptfor-loopargumentssettimeoutdelay

Execute Three Distinct Functions in for loop with delays


Say I have three functions that I want to run in sequence 5 times waiting one second between each one and the first one takes the variable in the for loop as an argument. Something like this:

for (var i=0; i<5; i++) {
   setTimeout(function(){
       one(i);
   },1000);
   setTimeout(function(){
       two();
   },2000);
   setTimeout(function(){
       three();
   },3000);
}

I have tried this and it doesn't seem to work. How can I fix this?


Solution

  • setTimeout() sets up a timer to run a function in the future but returns immediately, so your function will run one() 5 times after 1 second, two() 5 times after 2 seconds and three() 5 times after 3 seconds.

    You could achieve your goal with

    for (var i=0; i<5; i++) {
       setTimeout(function(){
           one(i);
       },(i * 3 + 1) * 1000);
       setTimeout(function(){
           two();
       },(i * 3 + 2) * 1000);
       setTimeout(function(){
           three();
       },(i * 3 + 3) * 1000);
    }