5

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.

4
  • Why second snippet guarantee that the previous interval has completed?, it guarantees that previous AJAX is completed Commented Apr 29, 2016 at 4:36
  • @Tushar thats the question actually. Why not first can guarantee the same? Commented Apr 29, 2016 at 4:38
  • What if the AJAX took time more than 30000ms to complete Commented Apr 29, 2016 at 4:39
  • In case of second approach, setTimeout only gets called once first time. And it gets called again in the callback of ajax. So it guarantees that the ajax call is complete before the second time execution starts. While in case of first approach, regardless of ajax result, setInterval keeps calling function at regular interval. It does not care whether the call back arrives as a result of previous execution. Hope this helps. Commented Apr 29, 2016 at 4:43

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.