如何在不降低网页速度的情况下降低自定义Javascript扩展的速度?

时间:2019-05-30 02:56:06

标签: javascript google-chrome google-chrome-extension

我有一个自定义的javascript扩展程序,可以解决网站上的调查。不幸的是,它的工作原理有点太好了-它选中了复选框,然后很快就点击了下一个。该网站检测到这一点,意识到这是一个解决调查的机器人,然后发送错误消息,指出请求过多。我可以使用什么代码来减慢不会停止网站的扩展程序?

我专门尝试使用我自己编写的sleep()函数,该函数基本上完全停止了javascript程序。我只是在checkBox方法之前写了一个快速的“ sleep(1500)”。实际上,这最终会导致整个页面停止javascript,这与我想要的完全相反。

setInterval

我的目标是让扩展程序等待大约3至4秒钟,然后再选中该框并单击,然后再等待3到4秒钟,依此类推。实际发生的事情是在花哨之前该网页已完成的复选框的动画,该扩展程序已经选中了右侧的框,然后点击了下一步。如前所述,这太快了。基本上,我想让扩展程序停顿3秒钟,同时让网页上的javascript继续运行。

1 个答案:

答案 0 :(得分:-1)

有三种方法可以实现这一目标。

第一种方法是跳过制作sleep()函数,而只使用setTimeout()

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

另一种方法是使用async / await,如下所示。

// 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);

但是,IE不支持异步/等待,因此,如果您希望支持异步/等待,最好的方法是使用setInterval()。必须将时间间隔分配给变量,否则您将无法停止它,并可能导致某些问题。

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
});
相关问题