Deepak Ingole
Deepak Ingole

Reputation: 15742

recursive setTimeout pattern

While reading an article on Long Polling I got little confused between following two flavors of setInterval

1 -

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

2-

(function poll() {
   setTimeout(function() {
       $.ajax({ url: "server", success: function(data) {
            sales.setValue(data.value);
       }, dataType: "json", complete: poll });
    }, 30000);
})();

As per blog it says - About second snippet,

So, this pattern doesn't guarantee execution on a fixed interval per se. But, it does guarantee that the previous interval has completed before the next interval is called.

Why second snippet guarantee that the previous interval has completed?

I know about first (Event loops) but little confused about second snippet.

Upvotes: 5

Views: 429

Answers (1)

guest271314
guest271314

Reputation: 1

Why second snippet guarantee that the previous interval has completed?

At first example $.ajax() is called at an interval, whether or not previous $.ajax() call completes.

At second example poll is not called again until complete function of $.ajax().

Upvotes: 3

Related Questions