user23634623
user23634623

Reputation: 161

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:

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

Upvotes: 2

Views: 3525

Answers (3)

jfriend00
jfriend00

Reputation: 708146

Check out setInterval() to run something over and over. You can generate a random index from 0 to 2 with Math.floor(Math.random() * 3).

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. Instead, you use timers to do something repeatedly.

Upvotes: 3

Anders Elmgren
Anders Elmgren

Reputation: 658

setTimeout uses milliseconds and only occurs once. Use setInterval with one second * 60 to get a minute.

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

Upvotes: 0

Matthew Brooks
Matthew Brooks

Reputation: 571

You're looking for setInterval instead of setTimeout, which will invoke the callback indefinitely at the interval you specify.

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.

Upvotes: 3

Related Questions