-3

I am creating a Chrome extension that, while on a Udemy course page, checks all the videos, so the certificate will become available, but I am encountering a problem where I activate the click event on all the needed buttons, but this happens so fast that my console gets spammed with net::ERR_INSUFFICIENT_RESOURCES, and only half of all the buttons get clicked and send the POST request to the Udemy servers. Now I was looking for a sleep() function, and a google search told me there isn't one in javascript.

This is the code I am using.

function clickButtons() {
    var buttons = document.getElementsByClassName("curriculum-item--progress--3eKMJ btn btn-default")
    for (i = 0; i < buttons.length; i++) {
    clickButton(buttons, i)

}

}
function clickButton(buttonsArray, index){ 
    buttonsArray[index].click();
}

clickButtons();

If theres another way to circumvent this issue, that would also be appreciated.

Floern
  • 31,495
  • 23
  • 98
  • 115
  • 5
    use setTimeout ? – epascarello Feb 07 '19 at 01:37
  • or use lodash or underscore throttle method – Randy Casburn Feb 07 '19 at 01:37
  • You can use the simple method setTimeout to delay your function by an amount in milliseconds, check https://www.w3schools.com/jsref/met_win_settimeout.asp – Mathieu Dfr Feb 07 '19 at 01:38
  • 2
    Please don't make more work for other people by vandalizing your posts. By posting on Stack Overflow, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](https://creativecommons.org/licenses/by-sa/3.0) for SO to distribute that content. By SO policy, any vandalism will be reverted. If you want to know more about deleting a post, please take a look at [How does deleting work?](https://meta.stackexchange.com/q/5221) – iBug Feb 14 '19 at 19:35

2 Answers2

1

You could create a delay method using aync and await:

const delay = t => new Promise(res => setTimeout(res, t));

(async _ => { // declare as async (as we need to use await)
  console.log("Hello");
  await delay(2000); // 2000 m/s (2 second) delay
  console.log("World!");
})();

However, with that being said, I think it is best to maybe work out a callback of some sort which triggers another button click, which triggers the next etc...

Nick Parsons
  • 31,322
  • 6
  • 25
  • 44
0

There is a workaround/alternative. In your clickButtons() function you can wrap the call to clickButton with a setTimeout(). Like this:

setTimeout(function(){
    clickButton(buttons, i)
}, 2000); 

Which would delay each call in your loop by your set timeout.

Also referenced here JavaScript sleep/wait before continuing

seech
  • 1
  • 1
  • 2