0

I have a userscript which loads a list of buttons on a page. It then tries to click all the buttons one by one in a loop. This is my function.

const clickButtons = async function(listButtons) {
    const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
    for (let i = 0; i < filteredButtons.length; i++) {
        filteredButtons[i].click();
    }
}

The above piece of code works as expected. No issues. All the buttons are clicked.

But, when I try to add some wait time before every click, it doesn't work. None of the buttons get clicked. Notice wait() on first line inside the loop

const wait = async function(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}
const clickButtons = async function(listButtons) {
    const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
    for (let i = 0; i < filteredButtons.length; i++) {
        await wait(1000);
        filteredButtons[i].click();
    }
}

What am I missing here?

Shubham Rana
  • 370
  • 1
  • 4
  • 12
  • [I can't reproduce the issue](https://jsfiddle.net/gneza6pj/). Maybe the buttons changed in the mean time? – Ivar May 29 '21 at 18:03
  • @Ivar, I had that doubt. But I have verified that the elements don't change after the timeout – Shubham Rana May 29 '21 at 18:13
  • 1
    @Ivar it seems it was the buttons had changed after all, from a previous operation. I waited for a second before I fetch the buttons to be clicked so any previous operation doesn't affect it. It worked. Thanks! – Shubham Rana May 29 '21 at 18:34

2 Answers2

0

Resolving the promise with a click should work

await wait(1000).then((res)=> filteredButtons[i].click());
        
valerysntx
  • 506
  • 3
  • 7
0

You can try this:

const wait = async function(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}

const clickButtons = async function(listButtons) {
    const filteredButtons = Array.from(listButtons).filter(x => shouldButtonBeClicked(x.innerText));
    filteredButtons.forEach(async function (filteredButton, index) {
       await wait(1000);
       filteredButtons[index].click();
       // OR
       // filteredButton.click();
    });
}
Mohamed Ayadi
  • 83
  • 1
  • 8