首页 > 解决方案 > 如何创建函数以在 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 -->

标签: javascript

解决方案


您可以使用setIntervalfunction 重复调用函数并停止它,将您的setIntervalin 添加到变量中,然后clearInterval与变量名一起使用。

在您的脚本中添加此代码setInterval(repeateMyFunction, 1000);

它将repeateMyFunction每 1 秒调用一次函数。


推荐阅读