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


i using jqwidgets create pie chart. , while fine , dandy , working charm. i'd update data every x number of seconds. using jquery, here code have 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);     } } 

my issue is, if loadchart function called, instance of setinterval created, , after 3 or 4 times, chart in constant state of refresh. how optimize setinterval call 1 instance called?

thanks in advance.

you need clear existing interval before set new one. try following trick.

function loadchart(id, name) {     // use trick make our 'interval' var kinda static inside function.     // value not change between calls loadchart().     var interval = null;      // core of trick: replace outer function inner helper      // remembers 'interval' in scope.     loadchart = realloadchart;     return realloadchart(id, name);      function realloadchart(id, name) {         var speed = 5000;          // remove old interval if exists, set new 1         interval && clearinterval(interval);         interval = setinterval(reloaddata, speed);          function reloaddata() {             // ... code, no nothing interval here ...         }     } } 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -