Monday, January 26, 2015

Polling AJAX Requests in JavaScript

Polling AJAX is tricky. If the next interval triggers before the last AJAX request is complete, your app is doomed!! This creates a domino effect where your queue for requests fill up faster then it can complete. Your queue will NEVER finish… similar to an infinite loop.
In light of this, you should never put AJAX into a setInterval function. A clean, more robust option is this:
(function poll() {
    setTimeout(function () {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: 'http://somewhere.com/rest/123',
            success: function (data) {
                MyNamespace.myFunction(data); //DO ANY PROCESS HERE
            },
            complete: poll
        });
    }, 5000);
})();
 
 
Notice the “complete” event of the AJAX triggers the self-executing function. Instead of using setInterval, it is using setTimeout that waits for 5 seconds then calls the AJAX. The process starts again when the “complete” triggers, waits 5 seconds, calls the AJAX again, then complete triggers once more, and so forth. Your queue of requests will always be one. If you study this, you will realize how clean this is!

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More