RetroCode RetroCode - 4 months ago 26
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.


The above code only executes one click.

Even this code, execute only one click.

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 ?


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
   // increment and check value reached to `5`
   // if `5` then clear the interval
   if(++i == 5) clearInterval(inter);