Polling AJAX Requests in JavaScript

By June 6, 2012 Uncategorized No Comments

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!

References

The following two tabs change content below.

Basem Emara

Software Architect at Falafel Software
Basem has over 10 years experience as a consultant and developer for dozens of projects for educational, advocacy, non-profit, small business, enterprise, and governmental organizations. As an innovator who recognizes and leverages the power of the web, he has been able to help real estate agencies, schools, hospitals, wholesale distributors, shipping carriers, and other businesses pioneer their industries utilizing the best that today’s technology has to offer from a more creative point of view. Simple yet elegant is the key to his approach, as well as the belief that continual process improvement is always possible.

Latest posts by Basem Emara (see all)