What is the optimal way to use setInterval in jquery ajax calls?

夙愿已清 提交于 2019-12-06 15:47:38

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

Instead of using setInterval which calls the function over and over again you would be better off using the setTimeout function which will call the callback you specify just once. Once that callback is called you can once again call setTimeout and you'll stop having the problems you're having right now. Also you'll wait until the last call is done before you start doing another one which is also good. The code might look something like this with the change:

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);
    }
}

For a working poc you could see http://jsfiddle.net/9QFS2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!