Dipak Ingole Dipak Ingole - 7 months ago 26
Javascript Question

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.

Answer

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