GS_
GS_

Reputation: 1

JS - how to use setTimeout function inside of the for loop?

I have created the following simple script to push buttons on the website...

var b = document.querySelectorAll('.button'), count;
for(var count = 0; count < b.length; count++) {
b[count].click();
}

...and it's working but I wanted to build the setTimeout function into it, so the buttons are not pushed all at once but with delay (either fixed or random) after each iteration.

The most logical seemed to be the code below...

var b = document.querySelectorAll('.button'), count;
for(var count = 0; count < b.length; count++) {
setTimeout(function() {
b[count].click();
}, 2000);
}

...but it's not working at all. Is the setTimeout in the wrong place ? It's inside of the loop so I expected it to be ok... Plis advise.

Upvotes: 0

Views: 19

Answers (1)

ImFarhad
ImFarhad

Reputation: 3189

Use let which has a block scope. if you use var you will always get the last index's value.

const b = document.querySelectorAll('.button'), count;
for(let count = 0; count < b.length; count++) {
  setTimeout(function() {
    b[count].click();
  }, 2000);
}

or you can use forEach

Upvotes: 1

Related Questions