2

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

Dan
  • 211
  • 1
  • 8
  • 2
    Does this answer your question? [How do I add a delay in a JavaScript loop?](https://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop) – Ivar Jul 09 '22 at 12:04

2 Answers2

3

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

Dinesh
  • 812
  • 4
  • 14
  • Hey @Dinesh, you're code snippet raises an Error when you try to run it. – Beni Trainor Jul 09 '22 at 12:06
  • 1
    This is well covered [here already](https://stackoverflow.com/a/36018502/479156). As mentioned in [answer], please don't answer questions that have been asked many times already. Instead, vote or flag to close them as a [duplicate](https://stackoverflow.com/help/duplicates). – Ivar Jul 09 '22 at 12:08
  • Hi @BeniTrainor, can you please provide the error quickly in the comments – Dinesh Jul 09 '22 at 12:14
  • `"Uncaught ReferenceError: matchbtns is not defined"`. You mispelled `matchBtns`. – Beni Trainor Jul 09 '22 at 14:05
  • May be you have missed to give `const matchBtns = document.querySelectorAll('.classname')` – Dinesh Jul 09 '22 at 15:40
-2

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
    })
  • This does something different than what the question is asking for. This will exponentially increase the time between button clicks (first one waits 3 seconds, second one waits 6 seconds, third one waits 18 seconds, fourth one waits 72 seconds, etc). – robere2 Jul 10 '22 at 16:58