0

I have the following script that I run on Console mode in Chrome to automatically click on some buttons on the webpage. But I want to add a delay after each click so that it won't click all buttons at once. Please let me know how to proceed.

[].slice.call(document.querySelectorAll('.button')).forEach(function(button) {button.click();});
wishman
  • 744
  • 3
  • 12
  • 29

2 Answers2

1

You can use the request requestAnimationFrame function

delay(Array.from(document.querySelectorAll('.button')));

function delay(sequentialEvents) {
    if (sequentialEvents.length > 0) {
        requestAnimationFrame(function () {
            var btn = sequentialEvents.shift();
            btn.click();
            delay(sequentialEvents);
        });
    }
}

or the setTimeout function

delay(Array.from(document.querySelectorAll('.button')), 1000);

function delay(sequentialEvents, ms) {
    if (sequentialEvents.length > 0) {
        setTimeout(function () {
            var btn = sequentialEvents.shift();
            btn.click();
            delay(sequentialEvents, ms);
        }, ms);
    }
}
Sagi
  • 7,484
  • 3
  • 30
  • 36
1

Here you are. Try this one. Just made checkboxes instead of buttons to make it obvious.

var buttons = [...document.querySelectorAll('input[type="checkbox"]')];

function clickButton(buttons) {

  var len = buttons.length;

  if (len < 1) return false;
  
  setTimeout(() => {
    buttons[0].click();
    buttons.splice(0,1);
    clickButton(buttons);
  }, 1000);
}

window.onload = clickButton(buttons);
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
Sergey
  • 5,085
  • 4
  • 29
  • 61