frewper
frewper

Reputation: 1433

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: function(data){
                showUpdate(data);
              }, dataType: "text"});
            }, 15000);

But this means that there is an initial delay of 15 secs, before the polling starts, which is not desired in my case. How can i force the polling to start immediately?

Upvotes: 0

Views: 632

Answers (3)

gpvos
gpvos

Reputation: 2802

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

Upvotes: 0

Lee
Lee

Reputation: 10603

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

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382274

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.

Upvotes: 2

Related Questions