【问题标题】:What is the optimal way to use setInterval in jquery ajax calls?在 jquery ajax 调用中使用 setInterval 的最佳方法是什么?
【发布时间】:2013-09-25 02:07:22
【问题描述】:

我正在使用JQWidgets 创建一个饼图。虽然这一切都很好,花花公子,而且像魅力一样工作。然而,我想做的是每 x 秒更新一次数据。使用 jQuery,这是我到目前为止的代码:

function loadChart(id,name){
   //chart loads here
   var speed = 5000,
       t = setInterval(reloadData,speed);
   function reloadData() {
        source.url = 'data.php?id='+id;
        var dataAdapter = new $.jqx.dataAdapter(source);
        $('#pie').jqxChart({ source: dataAdapter });
        console.log('reloading pie...'+globalPieId);
        speed = 5000;
        clearInterval(t);
        t = setInterval(reloadData, speed);
    }
}

我的问题是,如果调用 loadChart 函数,会创建另一个 setInterval 实例,并且在三四次之后,图表处于不断刷新的状态。如何优化我的 setInterval 调用以便只调用一个实例?

提前致谢。

【问题讨论】:

  • 尝试改用setTimeout 并仅在您收到上次通话的回调时添加新的超时。 (您似乎已经在这样做了)
  • @lfxgroove 一针见血。放弃 interval 并用 timeout 替换它,应该只需要更改一些代码,然后你就可以摆脱 clearInterval,因为 timeout 会处理它。

标签: javascript jquery ajax setinterval


【解决方案1】:

与其使用setInterval 一遍又一遍地调用函数,不如使用setTimeout 函数,它只调用一次指定的回调。一旦调用该回调,您可以再次调用setTimeout,您将不再遇到现在遇到的问题。此外,您将等到最后一个电话打完,然后再开始打另一个电话,这也很好。更改后的代码可能看起来像这样:

function loadChart(id,name){
   //chart loads here
   var speed = 5000,
       t = setTimeout(reloadData,speed);
   function reloadData() {
        source.url = 'data.php?id='+id;
        var dataAdapter = new $.jqx.dataAdapter(source);
        $('#pie').jqxChart({ source: dataAdapter });
        console.log('reloading pie...'+globalPieId);
        speed = 5000;
        t = setTimeout(reloadData, speed);
    }
}

对于工作 poc,您可以查看 http://jsfiddle.net/9QFS2/

【讨论】:

  • 感谢您的回复。我刚试过这个,遇到了和以前一样的问题。一旦使用不同的参数再次调用 loadChart 函数,图表就会开始多次刷新(在我的情况下,它每 5 秒刷新两次,两个实例偏移 2 秒)
  • 你怎么称呼loadChart
  • 这个。 setInterval 至少可以说是有问题的。
  • @lfxgroove loadChart 在单击按钮时调用 onClick='loadChart(1,'all')'
  • 而且你根本没有在任何其他地方调用它? :/因为您发布的小提琴中出现问题的原因是我们调用了两次设置超时的函数。
【解决方案2】:

在设置新间隔之前,您需要清除现有间隔。试试下面的技巧。

function loadChart(id, name) {
    // We use a trick to make our 'interval' var kinda static inside the function.
    // Its value will not change between calls to loadChart().
    var interval = null;

    // This is the core of a trick: replace outer function with inner helper 
    // that remembers 'interval' in its scope.
    loadChart = realLoadChart;
    return realLoadChart(id, name);

    function realLoadChart(id, name) {
        var speed = 5000;

        // Remove old interval if it exists, then set up a new one
        interval && clearInterval(interval);
        interval = setInterval(reloadData, speed);

        function reloadData() {
            // ... your code, but no do nothing with interval here ...
        }
    }
}

【讨论】:

  • 谢谢,我会试试这个并回复你。
  • 这就像一个魅力!虽然我确实认为@lfxgroove 的方法在任何其他情况下都可以使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多