简体   繁体   English

每 1 分钟在 chrome 中运行一个脚本

[英]Run a script in chrome every 1 minute

im trying to make a script that picks 1 random class name out of 3 every 1 minute and clicks the button with the chosen class so far i created the script that clicks on the button:我正在尝试制作一个脚本,每 1 分钟从 3 个随机类名中选择 1 个并单击所选类的按钮,到目前为止我创建了单击按钮的脚本:

setTimeout(function () {
    $(".btn-danger").trigger("click");
}, 100);

The problem is if i put it in a while(true) the site stuck and then the browser crashes.问题是如果我把它放在一段时间(真的)网站卡住然后浏览器崩溃。

Also im have no idea how to make it to chose random class so i putted in one of them.我也不知道如何让它选择随机类,所以我选择了其中之一。

Will be glad to get some help here :D很高兴在这里得到一些帮助:D

Check out setInterval() to run something over and over.查看setInterval()一遍又一遍地运行一些东西。 You can generate a random index from 0 to 2 with Math.floor(Math.random() * 3) .您可以使用Math.floor(Math.random() * 3)生成从 0 到 2 的随机索引。

For example, you could select a random class name like this:例如,您可以像这样随机选择一个类名:

var classes = ["classA", "classB", "classC"];

function selectRandomArrayElement(array) {
    return array[Math.floor(Math.random() * array.length)];
}

var rand = selectRandomArrayElement(classes);

So, putting it all together:所以,把它们放在一起:

var classes = ["classA", "classB", "classC"];

function selectRandomArrayElement(array) {
    return array[Math.floor(Math.random() * array.length)];
}

// click on a the object with a random class name every minute
setInterval(function() {
    var rand = selectRandomArrayElement(classes);
    $("." + rand).trigger("click");
}, 1000*60);

In Javascript, you can't use while(true) long duration loops like this block the rest of the browser from processing events and thus your the click events you trigger are never processed.在 Javascript 中,您不能像这样使用while(true)长持续时间循环阻止浏览器的其余部分处理事件,因此您触发的点击事件永远不会被处理。 Instead, you use timers to do something repeatedly.相反,您可以使用计时器重复执行某些操作。

You're looking for setInterval instead of setTimeout , which will invoke the callback indefinitely at the interval you specify.您正在寻找setInterval而不是setTimeout ,它将在您指定的时间间隔无限期地调用回调。

setInterval(function () {
  $(".btn-danger").trigger("click");
}, 60000);

Should work for you.应该为你工作。 while(true) crashes your browser because you're creating an infinite loop that blocks any other code from executing. while(true)会使您的浏览器崩溃,因为您正在创建一个阻止任何其他代码执行的无限循环。

setTimeout uses milliseconds and only occurs once. setTimeout 使用毫秒并且只发生一次。 Use setInterval with one second * 60 to get a minute.使用 setInterval 和一秒 * 60 来获得一分钟。

var minute = 1000 * 60;
setInterval(function() {   $(".btn-danger").trigger("click");
  }, minute);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM