ilopno1
ilopno1

Reputation: 1

The click does not work at every iteration. How to make the click work in a loop?

I am just starting to learn JS.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

for (var j = 1; j < 1000; j++) {
  var input = document.querySelectorAll('[data]');
  for (var i = 0; i < input.length; i++) {
   input[i].click();
   console.log(i)
   sleep(158)
}}

In this code, the click() is made after the end of the loop for all elements. How can I fix the code so that the click() is triggered on every iteration?

Upvotes: 0

Views: 42

Answers (1)

GoldenretriverYT
GoldenretriverYT

Reputation: 4765

The reason it doesn't work is because you are halting the whole process for your browser. It has no time to execute the event listeners if you fill it with endless work. You should use async/await to sleep instead.

async function sleep(ms) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, ms);
    })
}

for (var j = 1; j < 1000; j++) {
    var input = document.querySelectorAll('[data]');
    for (var i = 0; i < input.length; i++) {
       input[i].click();
       console.log(i)
       await sleep(158);
    }
}

You might will need to wrap your for loop in an async function for this to work. Just do (async() { ...... the code of your loop ...... })(); to do that.

Upvotes: 1

Related Questions