-1

My Code

window.onload = function(){
  setInterval(function(){
    if (typeof document.getElementsByClassName('btn-primary')[0]!="undefined"){
        document.getElementsByClassName('btn-primary')[0].click();
    }
  }, 1000);
}
<button type="button" class="btn-primary" >Auto click</button>

i want to click button as class="btn-primary" only 10 time. but i won't find the code for it. my code repeats clicking every 1s.

Now my question is, how can i click the button only 10 times?

1 Answers1

2

If you are using setInterval function, that function will trigger each time on the specified interval, you have to use clearInterval once the limit is reached.

function clickme() {
  console.log('You clicked me');
}
let intervalFunction;
let count = 0;
window.onload = function () {
  intervalFunction = setInterval(function () {
    if (typeof document.getElementsByClassName('btn-primary')[0] != "undefined") {
      document.getElementsByClassName('btn-primary')[0].click();
      count++;
      if (count === 10) {
        console.log("Now you have clicked me 10 times!! let me take a break")
        clearInterval(intervalFunction)
      }
    }
  }, 1000);
}
<button class="btn-primary" onclick="clickme()">Click me</button>

If you dont need to have the interval between each click, you can direcly click it with a loop.

Example

function clickme() {
  console.log('You clicked me');
}
let intervalFunction;
let count = 0;
window.onload = function () {
  while(count < 10) {
    if (typeof document.getElementsByClassName('btn-primary')[0] != "undefined") {
      document.getElementsByClassName('btn-primary')[0].click();
      count++;
    }
  }
}
<button class="btn-primary" onclick="clickme()">Click me</button>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49