0

I have to keep polling a server for informations, so I set this recursive function:

function getStats(){ 
 $.getJSON("Stats", function(statList){
            //parse the statList and update page's html

            setTimeout(getStats(), 5000);//recalling
 });
}

Looking at wireshark I see that the frequency is NOT every 5 seconds like it should! How come?

And while we are at it...this function is executed in a jquery tab, I'd like that when I change tab it just stops sending requests..how to do this too?

Phate
  • 6,066
  • 15
  • 73
  • 138

2 Answers2

2

If you want to use repeatedly, you should use setInterval instead of setTimeout

setInterval(function () {
$.getJSON("Stats", function (statList) {
    //parse the statList and update page's html


});
}, 3000);

setTimeout(); will execute only once. Also there is a problem with your calling of setTimeout, ie dont need to use () in specifying the method. Your call should look like

setTimeout(getStats, 5000);

Edit

 function getStats() {
  $.getJSON("Stats", function (statList) {
       //parse the statList and update page's html

  });
}
getStats();
setInterval(getStats, 5000);
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
  • Problem is that this way first execution takes 5 seconds too, while I'd like for it to be executed instantly – Phate Mar 28 '14 at 10:21
  • Another thing...and if I wanted to pass a paramether to my function? – Phate Mar 28 '14 at 12:45
  • take a look at these solutions. It definitely will help you http://stackoverflow.com/questions/457826/pass-parameters-in-setinterval-function – Anoop Joshi P Mar 28 '14 at 15:53
0

See:

setTimeout(getStats(), 5000);

getStats() is a function so you don't need to apply ().

You are using as a callback function of this method so it has to be like:

setTimeout(getStats, 5000);

see this:

setTimeout(fn, time_in_ms);

or

setTimeout(function(){
  // here you can call your function
}, time_in_ms);
Jai
  • 74,255
  • 12
  • 74
  • 103