0

I am implementing the setTimeout function inside 'for loop', which doesn't seem to work as expected.

Here's the codes I used:

var listItems = ['1','2','3'];

for(var i = 0 ; i < listItems.length ; i++){
    setTimeout(function(){
      console.log(listItems[i])
    },500)
}

Tested, returns 'Undefined (3)'

Baffled, tried another solution

var listItems = ['1','2','3'];
for(var i = 0 ; i < listItems.length ; i++){
    setTimeout(function(i){
      console.log(listItems[i])
    },500)
}

Obviously this wasn't even valid.

Looked on another similar question here, and tried:

var listItems = ['1','2','3'];
for(var i = 0 ; i < listItems.length ; i++){

    (function(){
      setTimeout(function(){
        console.log(listItems[i])
      },500)
    })(i);

}

Still 'undefined(3)'

This is the working code without the setTimeout function. I am not sure what I am doing it wrong.

Thanks!

Yongju Lee
  • 241
  • 4
  • 5
  • Your last try seems to be the good one, you just forgot to declare the argument on the Self Invocation Function. (function(value){ setTimeout(function(){ console.log(value) },500) })(listItems[i]); – Disfigure Apr 06 '18 at 13:33
  • @jonas, it does no explain the wrong use of the closure which does not have a parameter, but the inner function has one, but this in nerver used. – Nina Scholz Apr 06 '18 at 13:33
  • @nina so you want to add an answer for this: `(function(i){` ?! Then the OP hasnt read the explanations carefully. – Jonas Wilms Apr 06 '18 at 13:36
  • i missed a comment for this, guided with closing – Nina Scholz Apr 06 '18 at 13:37
  • the problem is that `i` is locally scoped, you do not need all these closures, you can, in fact, just assign a new value your indexer, and leave your first example as-is.. i.e. `let n = i` .. and then `console.log(listItems[n])` – Napoli Apr 06 '18 at 13:38
  • @Disfigure Tried it, and that seems to work. Thanks for the answer & explanation! I will look it up further. – Yongju Lee Apr 06 '18 at 13:39
  • @YongjuLee your answer can also be found in the duplicate question, pertinent to you, answer #4 (which is what i stated above) – Napoli Apr 06 '18 at 13:43

0 Answers0