触发鼠标单击和随机间隔

时间:2017-01-03 18:38:42

标签: javascript jquery html

我正在尝试自动完成一项任务,我必须不断地在手形图标上单击鼠标左键。我能够在设定的时间范围内完成此操作,例如32秒和756毫秒,但我需要在随机时间范围内完成此操作。例如,如果我们可以在每次鼠标左键单击后添加2-3秒。任何人都可以指导我如何使点击间隔随机?我正在使用Chrome。

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

4 个答案:

答案 0 :(得分:3)

使用在setTimeout之后调用自身的递归函数。这将无限运行,每次都以32000到35000毫秒(32到35秒)之间的随机间隔运行。

var clickHand = function() {
  $("[id^='hand_'].handIcon").trigger('click');
  setTimeout(clickHand, (Math.random() * 3000) + 32000);
}

clickHand();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:2)

即使您在setInterval中使用Math.random,它也只会使用该特定随机值注册一次。

有两种选择:

  • 运行一次,然后使用新的随机时间帧重新注册(使用clearInterval删除旧的时间帧)
  • 每x毫秒运行并添加随机检查以查看是否运行

EG。第二种情况:

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

这将每200毫秒运行一次,但只有0.8次,例如平均每250毫秒,但是随机的。当然,你可以调整数字。

第一个例子,因为我今天真的受到启发(rs):

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

答案 2 :(得分:0)

您的答案是setTimeout作为具有随机延迟的回调

var timeout = function(callback) {
   var time = Math.floor(Math.random()*32756);
   return setTimeout(function(){
      callback();
      timeout(callback);
   }, time)
};

timeout(function(){
   $( "[id^='hand_'].handIcon").trigger('click');
})

答案 3 :(得分:0)

而不是setInterval使用setTimeout。然后它只运行一次,你可以在那段时间后设置一个新的(随机)超时。您可以将其包装在一个很好的函数中,该函数可以与setIntervalsetTimeout类似的方式调用,但是使用范围而不是单个值。

&#13;
&#13;
// Generic function to set this interval
function setRandomInterval(f, min, max) {
  setTimeout(function() {
    f();
    setRandomInterval(f, min, max) 
  }, min + Math.random() * (max - min));
};

// Calling it, specifying a min and a max timeout
setRandomInterval(function(){

  console.log(new Date()); // For demo
  //$( "[id^='hand_'].handIcon").trigger('click');

}, 200, 3000);
&#13;
&#13;
&#13;

相关问题