什么是使用的setInterval jQuery的AJAX调用的最佳方式?方式、setInterval、jQuery、AJAX

2023-09-10 20:41:41 作者:何以笙箫默

我使用 JQWidgets 创建饼图图表。虽然这是所有罚款和花花公子而像一个魅力的工作。我想不过做的是更新数据每隔x秒数。使用jQuery,这里是code,我到目前为止有:

I am using JQWidgets to create a pie chart. And while that is all fine and dandy and working like a charm. What I'd like to do however is update the data every x number of seconds. Using jQuery, here is the code that I have so far:

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调用,以便只有一个实例被称为?

My issue is, that if the loadChart function is called, another instance of setInterval is created, and after three or four times, the chart is in a constant state of refresh. How do optimize my setInterval call so that only one instance is called?

在此先感谢。

推荐答案

您需要清除现有的区间,然后建立一个新的。试试下面的技巧。

You need to clear existing interval before you set up a new one. Try the following trick.

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 ...
        }
    }
}