Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 387
Deepak Ingole Avatar asked Oct 18 '22 10:10

Deepak Ingole


1 Answers

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().

like image 108
guest271314 Avatar answered Nov 03 '22 17:11

guest271314