RetroCode RetroCode - 3 months ago 18
jQuery Question

Execute Multiple Clicks

I am trying to click a button multiple times. Each time the button is clicked, it loads for 1 second, reappears and is able to be clicked again. I want to click this button 5 times.

for(i=0;i<5;i++)
$('.class').click();


The above code only executes one click.

Even this code, execute only one click.

for(i=0;i<5;i++)
setTimeout(() => $('.class').click(),2000);


If I do the step manually , that is if I enter $('.class').click() to the console five times, it works. Any idea as to why ?

Answer

Multiply the delay with the i since for loop does not wait for executing the setTimeout callback.

for(i = 1;i <= 5; i++) 
  setTimeout(() => $('.class').click(),i * 2000);

Another way is to use setInterval method along with clearInterval.

// variable for count
var i = 0;
// reference for clearing interval
var inter = setInterval(()=>{
   // trigger click event
   $('.class').click(); 
   // increment and check value reached to `5`
   // if `5` then clear the interval
   if(++i == 5) clearInterval(inter);
},2000);