0

Basically, i have a loop where if a certain condition is met, it fires a setTimeout. But the timeout function requires the value of the loop ( i.e 'i'), as example below. How do i do that?

 for( var i = 0; i <= 10; i++) {
    if(something){
      setTimeout(function(){
         console.log(i);
      }, 1000);
    }
 }
Pratish Shrestha
  • 1,712
  • 4
  • 17
  • 26
  • FYI, modern browsers let you pass extra arguments to `setTimeout` which show up as callback arguments. `setTimeout(function(i) { console.log(i); }, 1000, i);` –  Jan 02 '16 at 17:34

2 Answers2

2

Use IIFE (immediately-invoked function expression), it is a JavaScript design pattern which produces a lexical scope using JavaScript's function scoping.

 for( var i = 0; i <= 10; i++) {
    if(something){
        (function(i){
            setTimeout(function(){
               console.log(i);
            }, 1000);
         })(i);
     }
 }
void
  • 36,090
  • 8
  • 62
  • 107
0

for (var i = 0; i <= 10; i++) {
  if (true) {
    setTimeout((function(i) {
     return function() { console.log(i); }
    })(i), 1000 * i);
  }
}

and I think you want the time to be 1000 * i ? (It's already in the code above)

CoderPi
  • 12,985
  • 4
  • 34
  • 62