Phate
Phate

Reputation: 6612

Ajax requests seems to not respect the timer

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?

Upvotes: 0

Views: 48

Answers (2)

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

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

Upvotes: 2

Jai
Jai

Reputation: 74738

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

Upvotes: 0

Related Questions