-1

I have a custom javascript extension that solves a survey on a website. Unfortunately, it works a little too well - it checks the check box and hits next too fast. The website detects this, realizes it's a bot that's solving the survey, and sends an Error, saying that there's too many requests. What code can I use to slow down my extension that won't stop the website?

I've specifically tried to use a sleep() function that I wrote myself which basically stalls the javascript program entirely. I just write a quick "sleep(1500)" before the checkBox method. This actually ends up stopping the javascript on the entire page, which is the exact opposite of what I want.

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

I'm aiming to have the extension wait roughly 3 to 4 seconds before checking the box and hitting next, after which, it'll wait another 3 to 4 seconds, etc. The actual thing that happens is that before the fancy animation for the checkboxes that the webpage has finishes, the extension's already checked the right box and has hit next. As stated, this is way too fast. Basically, I want to stall the extension for 3 seconds, while letting the javascript on the webpage continue working.

CuriousBo
  • 11
  • 2
  • 2
    Possible duplicate of [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – Herohtar May 30 '19 at 03:13

1 Answers1

-1

There are three ways you can achieve this.

The first way is to skip making a sleep() function and instead just use setTimeout().

// code before wait
setTimeout(()=>{
    // code after wait
}, 1500);

Another way is to use async/await as shown below.

// Promises require async/await to work in JavaScript
async function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms); // this will call the resolve() function after the time has passed
    });
}

// You cannot use await in a non-async function, be sure to change that before adding this
await sleep(1500);

However, async/await is not supported in IE, so if you are looking to support it the best way is to use setInterval(). The interval must be assigned to a variable, otherwise you cannot stop it and may cause some issues.

function sleep(ms, todo) {
    var started = Date.now(); // get current time before wait
    var temp = setInterval(()=>{
        if ((Date.now() - started) > 1500) {
            clearInterval(temp); // stops the interval from repeating
            // avoid "X is not a function" errors
            if (typeof todo === 'function') todo(); // perform the code to do after the wait
        }
    }, 50);
}


// your code before the sleep function

sleep(1500, function() {
    // the code after the sleep function
});
vns
  • 1
  • 2