setTimeout inside for loop [Help needed]

setTimeout inside for loop [Help needed]
0.0 0

#1

I’m making Simon game setTimeout function is not working as expected.
n is being logged in to console and glow() is being called without any delay.
I researched it on stack and found that its some closure issue I fixed it but still not working pls help finding whats wrong with this code…

for(let i = 0; i < glows.length; i++) {
                (function(n) {
                    setTimeout(function(){
                            console.log(n);
                            glow(glows[n]);
                            let audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
                            audio.volume = 0.2;
                            audio.play();                    
                    }, 1000);
                }(i));
            }

Simplified code…

<a class="btn btn-primary m-5" href="#" id="button" role="button">Button</a>
   <script>
    $("#button").click(function() {
        for(let i = 0; i < 5; i++) {
                (function(n) {
                    setTimeout(function(){
                            console.log(n);
                    }, 1000);
                }(i));
            }
    });
    
    </script>

#2

Note that the for loop does not wait for a second every iteration, but rather creates the 5 timeouts in a few milliseconds. Then, after 1 second all those timeouts ‘expire’ and 0,1,2,3,4 is printed to the console.

One simple way to solve this:

setTimeout(function(){
   console.log(n);
},  n*1000);

Note that you don’t need the function wrapper when using ‘let’ instead of ‘var’:

for(let i = 0; i < 5; i++) {
   setTimeout(function(){
    console.log(i);
  }, i*1000);
 }

#3

Thanks @BenGitter , can you/anyone pls tell me simple way to synchronously execute the statements after this loop/timeout.

for(let i = 0; i < 5; i++) {
   setTimeout(function(){
    console.log(i);
  }, i*1000);
 }
console.log("loop/timeout is done");

#5

UsingsetTimeout in the way suggested here works, but it defeats the purpose of setTimeout. If you want repeated behaviour of the type: wait, do something, wait, do something, then use setInterval.


#6

I’ve got the solution Here