0

Javascript code

var inputs = document.getElementsByClassName('_42ft _4jy0 FriendRequestAdd addButton _4jy3 _517h'); 
for(var i=0; i<inputs.length;i++) { 
    inputs[i].click();8 
}

How do I add a one second delay in the loop?

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
Obada Diab
  • 77
  • 6
  • You could use recursion. Why is there an '8' after the ';'? – Pyromonk May 20 '17 at 04:23
  • Possible duplicate of [How do I add a delay in a JavaScript loop?](http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Pyromonk May 20 '17 at 04:25
  • Although this question is a duplicate, it is worth reiterating that the answer to this question is "you don't". This is _not_ how JavaScript works. If you want to generate 100 clicks, each one second apart, _you do not use a for loop_. – Ray Toal May 20 '17 at 04:28

1 Answers1

-1

You could use the setTimeout method, something like this should work. What setTimeout does is execute the code after the amount of ms specified as a second argument. In this case we use closures to make sure we pass in the right index when the function gets called, otherwise you end up calling the click() on the same value of i for every call.

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

Edit: You should probably provide more info on what you're final goal is and why you need this specific functionality. There might be different approaches that don't require to add a delay like the one proposed in this answe and request from you.

G4bri3l
  • 4,996
  • 4
  • 31
  • 53
  • Saying that there is no other way is simply incorrect. There's at least two more ways: requestAnimationFrame and busy looping. – Ingo Bürk May 20 '17 at 05:21
  • And it's also wrong because it doesn't wait one second *in between* the clicks. – Ingo Bürk May 20 '17 at 05:23
  • I never said there is no other way, you might wanna read the edit. Nowhere in the question is asked for one second delay in between the clicks. It's asked to delay by one second in the loop. Please read more carefully. – G4bri3l May 20 '17 at 13:40
  • You said "you definitely need to use", which means you say there is no other way. And if you want to delay all clicks as a whole by one second you should delay the loop, not the loop body. You're just creating unnecessary timeouts and anonymous functions. – Ingo Bürk May 21 '17 at 12:32
  • I understand your confusion, I'm sure other people will understand it the same way and in that case you're right I should probably edit to avoid any confusion. I still disagree with the rest, if he asks for a delay `in` the loop that does not meant a delay `of` the loop. That's not what he/she asked, and apparently the solution I provided was what he/she was looking for =) – G4bri3l May 22 '17 at 16:20