Trigger mouse click and random intervals


I am trying to automate a task where I have to continuously do left mouse click on an hand icon. I am able to do that on a set time frame, for example 32 sec and 756 ms but I need to do this with a random timeframe. For example if we can add 2-3 seconds after each left mouse click. Can anyone guide me how to make the click interval random? I am using Chrome.

    $( "[id^='hand_'].handIcon").trigger('click');
}, 32756);

Show source
| javascript   | jquery   | html   2017-01-03 19:01 4 Answers

Answers to Trigger mouse click and random intervals ( 4 )

  1. 2017-01-03 19:01

    Even if you use a Math.random at the setInterval, it will only register once, with that specific random value.

    There are two options:

    • run once and then re-register with a new random timeframe (use clearInterval to remove the old ones)
    • run every x ms and add a random check to see whether to run or not

    Eg. of the second case:

    setInterval(function() { 
      if (Math.random() > 0.8)
        $( "[id^='hand_'].handIcon").trigger('click');
    }, 200);

    This will run every 200ms, but only 0.8 of the times, e.g., on average every 250ms, but random. You can tweak the numbers, of course.

    Example of the first one, because I'm really inspired today (rs):

    let action = () => $( "[id^='hand_'].handIcon").trigger('click');
    let old, register = () => {
      if (old) clearInterval(old);
      old = setInterval(() => {
        register(); // re-register
      }, 32756 + 3000*Math.random() - 1500)
  2. 2017-01-03 19:01

    Use a recursive function that calls itself after a setTimeout. This will run infinitely, and each time at a random interval between 32000 and 35000 milliseconds (32 to 35 seconds).

    var clickHand = function() {
      setTimeout(clickHand, (Math.random() * 3000) + 32000);
    <script src=""></script>

  3. 2017-01-03 19:01

    Your answer is setTimeout as callback with random delay

    var timeout = function(callback) {
       var time = Math.floor(Math.random()*32756);
       return setTimeout(function(){
       }, time)
       $( "[id^='hand_'].handIcon").trigger('click');
  4. 2017-01-03 19:01

    Instead of setInterval use setTimeout. Then it will run only once, and you can set a new (random) timeout after that period. You can wrap it in a nice function which can be called in a similar fashion as setInterval and setTimeout, but with a range instead of a single value.

    // Generic function to set this interval
    function setRandomInterval(f, min, max) {
      setTimeout(function() {
        setRandomInterval(f, min, max) 
      }, min + Math.random() * (max - min));
    // Calling it, specifying a min and a max timeout
      console.log(new Date()); // For demo
      //$( "[id^='hand_'].handIcon").trigger('click');
    }, 200, 3000);

Leave a reply to - Trigger mouse click and random intervals

◀ Go back