【问题标题】:How to make my function loop every x second in javascript如何让我的函数在javascript中每x秒循环一次
【发布时间】:2017-01-18 21:27:26
【问题描述】:

谁能帮助我,让函数myFunction 每隔X 秒运行一次。如果我只运行一次,该功能就可以完美运行,但是当我开始使用 setInterval 时,它不会每 x 秒运行一次。在下面的示例中,它有时在 5 秒后执行,有时在 8 秒后执行,依此类推。我应该在我的代码中更改什么?我使用的 api 每分钟只授予 30 个请求,我担心这个函数会超过限制,因为有两个 getJSON。

setInterval(function () {
    myFunction();
}, 10000);

function myFunction() {

    $.getJSON("URL", function (data) {
        console.log(data);
        $.getJSON("URL", function (data2) {
            console.log(data2);

            variable1 = data.Departure;
            variable2 = data2.Departure;

            text = "";
            variable3 = variable1.concat(variable2);
            variable3.sort(function (a, b) {
                return new Date('2017/01/16 ' + a.time) - new Date('2017/01/16 ' + b.time);
            })

            console.log(variable3);
            for (var i = 0; i < variable3.length; i++) {
                text += variable3[i].name.substring(13, 19) + " departure " + variable3[i].time.substring(0, 5) + " from " + variable3[i].stop.substring(8) + "<br>";
            }
            document.getElementById("Textn").innerHTML = text;
            console.log(text);

        });
    });
}

myFunction();

【问题讨论】:

  • setTimeout 函数每 x 秒运行一次。 developer.mozilla.org/es/docs/Web/API/WindowTimers/setTimeout
  • 你怎么知道需要 5 秒、8 秒等?
  • @jaikl 你怎么知道你的函数需要多少时间?
  • setTimeout 函数只运行一次@Roy
  • @JamesMonger 我计算了函数运行的时间。至少需要 10 秒才能确定有问题。

标签: javascript json setinterval


【解决方案1】:

当前实现的问题是它使用异步请求可能需要超过 10 秒(无法预测何时提供请求)。

无论之前的请求是否完成,setInterval 方法都会执行myFunction

因此,下一个请求将排队等待执行。所以你会得到它有时会在 5 秒后执行,有时会在 8 秒后执行,依此类推。

您应该使用setTimeout() 来递归调用该方法,而不是使用setInterval

function myFunction() {
    $.getJSON("URL", function (data) {
        $.getJSON("URL", function (data2) {
            //Your existing code

            //Schedule it be executed after x * 1000 milliseconds
            setTimeout(myFunction, 10000);
        });
    });
}
myFunction();

【讨论】:

    【解决方案2】:

    示例 setInterval 实现,它将每 1 秒运行一次。 您的代码应该每 10 秒调用一次函数,找不到任何问题。

    setInterval(myFunction, 1000); 
    
    function myFunction(){
     console.log((new Date()).getSeconds());
    };
    
    myFunction();

    【讨论】:

    • 尚未回答背后的原因有时会在 5 秒后执行,有时会在 8 秒后执行,以此类推。
    【解决方案3】:

    试试这个:

    callfunction();
    var callCount = 1;
    var repeater = setInterval(function () {
      if (callCount <= 30) {
        callfunction();
        callCount += 1;
      } else {
        clearInterval(repeater);
      }
    }, 1000);
    
    function callfunction()
    {
      console.log((new Date()).getSeconds());
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2017-10-19
      • 2021-12-30
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多