Search code examples
javascriptjquerypolling

Polling a URL with setTimeout without delaying first poll


I'm using the code snippet found here (http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery):

(function poll(){
   setTimeout(function(){
      $.ajax({ url: "server", success: function(data){
        //Update your dashboard gauge
        salesGauge.setValue(data.value);

        //Setup the next poll recursively
        poll();
      }, dataType: "json"});
  }, 30000);
})();

to poll a local URL on a frequent basis to check the status of a record. However I also want to execute the poll immediately after page load whereas the above snippet initiates a loop which only first fires after the timeout period (30 secs in this case).

How can I modify the above to poll immediatley and then subsequently every 30 seconds. :)

TIA!


Solution

  • just move your settimeout

    (function poll(){       
          $.ajax({ url: "server", success: function(data){
            //Update your dashboard gauge
            salesGauge.setValue(data.value);
            setTimeout(poll, 30000);            
          }, dataType: "json"});      
    })();