0

I'm trying to add a pause between clicks when clicking on buttons in a page.

It's giving me "Uncaught TypeError: Cannot read property 'click' of undefined"

var inputs = document.getElementsByClassName('xxxxxx'); 

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

Not sure how else to approach it. If I remove the timeout, the clicks work properly.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – user3 Jan 28 '17 at 13:26

2 Answers2

2

This is a problem called "closing over the loop variable". What's happening is that when your timeout actually fires, i is equal to inputs.length, which is beyond the end of the set of inputs.

Simplest solution: use Array#forEach so that you have a separate closure containing each input itself and a separate, non-fluctuating copy of i, instead of an i variable that keeps changing:

var inputs = document.getElementsByClassName('xxxxxx'); 

Array.prototype.slice.call(inputs).forEach(function (input, i) {
     setTimeout(function () { 
         input.click(); 
     }, 1000 * i);
});    
JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

Try testing for the input if null :

if (inputs[i] != null) {
inputs[i].click();}

and try starting the timer on document complete.

Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17