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();});
3
  • stackoverflow.com/questions/951021/… Commented Apr 21, 2018 at 13:46
  • @JorgeFuentesGonzález as far as I know it all will "burst" after specified delay. Commented Apr 21, 2018 at 13:50
  • 1
    @Sergey He has to add different defays to each button, or better, execute the next button click after each delay. Commented Apr 21, 2018 at 13:52

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.