Over a million developers have joined DZone.

Quick Tip – Long Polling Using jQuery

·

Yesterday, I helped to write infrastructure code for a JavaScript SDK API that one of my customers is building right now. One of the things that needed to be implemented as part of the SDK was the functionality of long polling. Since the SDK has a dependency on jQuery, here is the code snippet that we used as starting point to write the implementation:

function longPoll(){
    $.ajax({ 
        url: "put here the server endpoint url",
        success: function(data){
            // do whatever you want with the data you received
        },
        error: function(err) {
            // do whatever you want when error occurs
        },
        type: "GET", 
        dataType: "json", 
        complete: longPoll,
        timeout: 60000 // timeout every one minute
    });
}

In the snippet, you use the $.ajax function to start the long polling and in the complete option you use the same caller function (longPoll) to continue polling the server. Another thing to notice is the timeout option which is set to one minute.

The code is really simple and I hope it will help you the get started with long polling.

Topics:

Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}