javascript - 如何在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 次随机按钮?
解决方案
要修复您的代码,您需要:
- 递归的基本案例
- 将函数引用传递给 setTimeout。目前,您正在执行 clickByItself 并将其返回值(未定义)传递给 setTimeout。
- 不要在没有将时间增加 i 倍的情况下在循环中使用 setTimeout,因为 for 循环会将所有函数调用同时排队
- 或者,您可以使用“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/
推荐阅读
- angular - 是否可以在不使用第三方链接的情况下使用 typescript 获取公共 IP 地址
- javascript - Angular:错误 TS2322:类型 'Observable<{}>' 不可分配 ... 使用 share() 运算符
- python - ValueError:无法为具有形状“(?,1)”的张量“Placeholder_37:0”提供形状(891,)的值
- python-2.7 - 使用 Selenium Python 复制文本字段值时,HTML 表单不返回剪贴板?
- ios - 为 iPhone 应用程序获取 .IPA 文件
- c++ - 从 .ini 加载数据使我的游戏崩溃!我能做些什么?C++
- spring-mvc - 设置了 DB 毫秒值的 Spring 调度程序
- c# - 将字符串分隔到不在集合字典中的列表中
- java - 具有 2 个过滤条件的 java 流
- python - 从其他函数调用函数