Home > Net >  How to wait for x seconds before clicking the next button using Javascript
How to wait for x seconds before clicking the next button using Javascript

Time:07-10

I have this code that clicks on the elements. The purpose of these buttons is to open accordions. It works but I need to modify it a little bit so as to reduce the load on the server. At the moment, all the buttons are clicked at once which causes some buttons on the same page not to work.

I was wondering if there is a way to wait for at least 3 seconds before clicking on the next button. All the buttons share the same class name.

const matchBtns = document.querySelectorAll('.classname')
matchBtns.forEach(matchbtn => matchbtn.click())

I have tried to wrap the forEach inside the setTimeout but I can't get it to work.

I tried

setTimeout(function() { matchBtns.forEach(matchbtn => matchbtn.click());}, 3000);

Thanks

CodePudding user response:

You can change your implementation something like this

const matchBtns = document.querySelectorAll('.classname')

let nextClickIn = 0;
let delay = 3000;
matchbtns.forEach((matchbtn) => {
    setTimeout(() => {matchbtn.click()}, nextClickIn)
    nextClickIn  = delay
})

Note: Provide the delay value in milliseconds

CodePudding user response:

You can code this one as below:

    const matchBtns = document.querySelectorAll('.classname')

    let nextClick = 1;
    let delay = 3000;
    matchbtns.forEach((matchbtn) => {
        setTimeout(() => {matchbtn.click()}, delay)
        nextClick  ;
        delay *= nextClick
    })
  • Related