[Solved] setTimeout in a for loop with array as an argument misbehaving


I noticed a couple of issues with your code.

  1. You are calling setTimeout in a loop. So if you have, say, numOfbox.length === 15, setTimeout will be called 15 times around 10,000 ms from when you set it. Could this be the reason you’re seeing the more calls to startGame than you thought?

  2. I see the variable numOfbox, but since it’s not declared in the startGame function I’ll have to assume that it’s in the parent scope. So, in the line where you do

    timeout[i] = setTimeout(startGame, 10000, numOfbox);
    

Realize that since numOfbox is in a higher level scope and startGame does not take any parameters, the numOfbox parameter (the 3rd argument in setTimeout) is really not going anywhere: the numOfbox variable actually uses is coming from the parent scope. This may be ok, but you should consider what is happening here.

11

solved setTimeout in a for loop with array as an argument misbehaving