首页 > 解决方案 > 如何在javascript中循环一个函数

问题描述

我有四种不同的按钮效果,每种效果都在一个变量中声明。

因此,我将所有这四个变量都放在一个名为 arr 的数组中,该数组在clickByItself()函数 using Math.floor(Math.random())methods 中使用。

如果没有for循环,每次我重新加载页面时,代码都会在四个按钮之一中随机单击。

function clickByItself() {
   let random = Math.floor(Math.random() * arr.length);
   $(arr[random]).click();
}

但是,使用for循环我无法在最多 10 次内一一进行这些点击。

var blueButtonEffect = code effect here;
var redButtonEffect = code effect here;
var greenButtonEffect = code effect here;
var yellowButtonEffect = code effect here;
var arr = [blueButtonEffect, redButtonEffect, greenButtonEffect, yellowButtonEffect];

//will click on buttons randomly
function clickByItself() {
    let random = Math.floor(Math.random() * arr.length)
    var i;
    for (i = 0; i < 10; i++) {
        $(arr[random]).click();
        setTimeout(clickByItself(), 1000);
    }
}

上面当前代码的最终输出是同时点击的四个按钮,而不是一个一个一个。

那么,我怎样才能让这个功能在每次点击后以一秒的间隔一个接一个地按 10 次随机按钮?

标签: javascriptjquery

解决方案


要修复您的代码,您需要:

  1. 递归的基本案例
  2. 将函数引用传递给 setTimeout。目前,您正在执行 clickByItself 并将其返回值(未定义)传递给 setTimeout。
  3. 不要在没有将时间增加 i 倍的情况下在循环中使用 setTimeout,因为 for 循环会将所有函数调用同时排队
  4. 或者,您可以使用“times”参数来避免循环

你可以尝试类似的东西

function clickByItself(times = 0) {
  let random = Math.floor(Math.random() * arr.length)
  $(arr[random]).click();
  if (++times < 10) {
    setTimeout(function(){clickByItself(times);}, 1000);
  }
}

控制台日志示例 https://jsfiddle.net/pfsrLwh3/


推荐阅读