0

I would like to execute a click on templates[i] within setTimeout within a for loop

for(var i=0; i<templates.length; i++){
    setTimeout(function(){
        (function(){
            templates[i].click();
        }(i, templates));
    }, 200);
}

I get the error templates[i] is undefined.

However, something like this works fine:

for(var i=0; i<templates.length; i++){  
    setTimeout(function(){
        (function(){
            console.log(templates_arr+templates)
        }(templates_arr, templates));
    }, 200);
}

Can anybody shed some light onto why this is like this and how I can pass the array and index properly?

Thanks, Dan

Dan Schalow
  • 146
  • 12
  • it is because by the time the IIFE is executed the value of `i` is changed to `templates.length` – Arun P Johny Jan 12 '16 at 09:29
  • It's a scoping issue. Once the timeout fires, `i` is no longer in scope. – Johannes Jander Jan 12 '16 at 09:29
  • 1
    So it should be `for (var i = 0; i < templates.length; i++) { (function(i, templates) { setTimeout(function() { templates[i].click(); }, 200); }(i, templates)); } ` – Arun P Johny Jan 12 '16 at 09:29
  • Thanks guys. Solves by passing a value which would definitely be the same at that moment in time. `for(var i=0; i – Dan Schalow Jan 12 '16 at 09:36
  • @ArunPJohny: yours is the elegant solution. I find the following easier to read, does it have any drawbacks? `for (var i = 0; i < templates.length; i++) { var func = function(template) { setTimeout(function() { template.click(); }, 200); }; func(templates[i]); }` – Johannes Jander Jan 12 '16 at 09:43
  • 1
    @JohannesJander you are creating multiple function instances, you can solve it by using `var func = function(template) { setTimeout(function() { template.click(); }, 200); }; for (var i = 0; i < templates.length; i++) { func(templates[i]); } ` – Arun P Johny Jan 12 '16 at 09:46
  • @ArunPJohny: Thanks, you are right. – Johannes Jander Jan 12 '16 at 09:48

1 Answers1

1

it should be

for(var i=0; i<templates.length; i++){
   (function(i,templates){
       setTimeout(function(){
            templates[i].click();
       }, 200);
   })(i, templates);

}
Oxi
  • 2,918
  • 17
  • 28