Skip to content Skip to sidebar Skip to footer

How To Start Polling Immediately?

I am trying to use polling for a small check that is performed at an interval of 15 secs. setInterval(function(){ $.ajax({ url: 'aaa.com', success: fun

Solution 1:

Don't look for smart solutions when simple ones do the job :

function check() {
   $.ajax({ url: "aaa.com",
     success: function(data){
     showUpdate(data);
   }, dataType: "text"});
}
check();
setInterval(check, 15000);

Alternatively, I'd generally prefer

function check() {
   $.ajax({ url: "aaa.com",
     success: function(data){
        showUpdate(data);
        setTimeout(check, 15000);
   }, dataType: "text"});  
}
check();

Because there wouldn't be a stack of calls in case of delayed response.


Solution 2:

Without getting into a slightly more complex idea of having a callback function which handles the delay between calls, the easiest method is to just move the function out to a named function and just call it manually the first time round

function doSomething() {

$.ajax({ url: "aaa.com",
                success: function(data){
                showUpdate(data);
              }, dataType: "text"});

}

doSomething();

setInterval(doSomething, 15000);

Solution 3:

How about just:

function immediatePoll(f, interval) {
    f();
    setInterval(f, interval);
}

immediatePoll(function(){
        $.ajax({ url: "aaa.com",
            success: function(data){
            showUpdate(data);
          }, dataType: "text"});
        }, 15000);

Post a Comment for "How To Start Polling Immediately?"