Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurate long polling example?

I've made an function that should do an long polling and fetch live data that is being "pushed" to me. Right now I'm testing against an json object that is formatted in the way that it will look once I receive the data. It seems as it is working accurate so far. I was merely wondering what you think about it? Would you refactor it somehow or do it entirely in another way?

var url = '../../path_to_script/respondents.json';

function fetchData() {
  $.ajax({
    url: url,
    method: 'GET',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    cache: false,
    success: function (data) {
        //parseData(data);
        setTimeout(function () { fetchData() }, 5000);
        console.log(data);
    },
    error: function (data) {
        setTimeout(function () { fetchData() }, 5000)
    }

 });

}

Regards

like image 708
Tim Avatar asked May 05 '11 07:05

Tim


1 Answers

This works like expected. Since you've wisely choosen to fire a setTimeout once the request returned, there can't be "overlapping" requests. That is a good thing.

Anyway, you could use jQuerys "new" deferred ajax objects which is probably a little bit more convinient.

(function _poll() {
    $.getJSON( url ).always(function( data ) {
        console.log( data );
        _poll();
    });
}());

Note: .always() is brandnew (jQuery 1.6).

Edit

Example: http://jsfiddle.net/rjgwW/6/

like image 110
jAndy Avatar answered Sep 25 '22 00:09

jAndy