javascript - 如何创建函数以在 1 秒后执行另一个函数多次
问题描述
我创建了函数名称myfunction()
,我需要创建另一个函数让我们调用它repeateMyFunction()
,我需要它在 1 秒后重复函数工作几次 + 我需要它使函数出现在多行中,而不仅仅是使用 for 循环或其他东西的 1 行,请无需创建新代码即可帮助我
1 = 尝试简单地将函数调用放入 myfunction() 2 = 尝试使用 for 循环来完成这项工作并重复该功能,但我做不到
结果我需要是这样的:
Ahmed will playing playstation: typeof is string
(1sec)
Ahmed was playing games: typeof is string
(1sec)
Ahmed is playing football: typeof is string
<!-- language: lang-js -->
function myFunction() {
var random = Math.floor((Math.random() * 3) + 0);
var templates = ["{{noun}} is {{verb}} football", "{{noun}} was {{verb}} games", "{{noun}} will {{verb}} playstation"];
var str = "{{noun}} is {{verb}} football";
var n = str.search("{{noun}}");
var y = str.search("{{verb}}");
var res = str.split(" ");
var list = [];
var str = templates[random];
var myis = str.slice(8, 13);
if (n != -1) {
list.push("Ahmed");
list.push(myis);
}
if (y != -1) {
list.push("playing");
}
var res = str.slice(22, 34);
var tryit = list.join(" ") + res;
document.getElementById("demo").innerHTML = tryit + ": typeof is " +
typeof(tryit);
}
<!-- end snippet -->
解决方案
您可以使用setInterval
function 重复调用函数并停止它,将您的setInterval
in 添加到变量中,然后clearInterval
与变量名一起使用。
在您的脚本中添加此代码setInterval(repeateMyFunction, 1000);
它将repeateMyFunction
每 1 秒调用一次函数。
推荐阅读
- java - 没有后缀时区的Java日期到字符串
- html - 如何将图片放在块的中心?
- amazon-web-services - 如何在 Amazon Keyspaces 中添加权限?
- .net - 本地主机与 Web 主机服务器上的 Vue 路由器行为
- r - 获取R中两个多面体之间的重叠百分比
- azure-log-analytics - 访问没有租户角色的工作簿?
- ui-automation - 计算空手道动态变化的网络表中的行数?
- html - 显示:flex 元素不会在父级中垂直增长
- snowflake-cloud-data-platform - Snowflake SQL - 如何将所有表的当前行数与 24 小时前的行数进行比较?
- python - 我如何循环数月,一次跳过三个?