Search code examples
javascriptarraysfor-loopsettimeoutself-invoking-function

Passing array and index within `for` loop and `setTimeout()`


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


Solution

  • it should be

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