Websocket con soporte Ajax Polling

Tenía la tarea de mostrar algunas actualizaciones de datos en tiempo real y decidí usar websockets. Una vez que implementé websockets, decidí ir un poco más allá y agregar un soporte Ajax Polling para navegadores que no tienen soporte para websockets.

var ajaxPolling = false;
var ajaxPollingTimeout = null;
var ajaxPollingTimer = 5; // seconds
var websocketPolling = true;
var websocketReconnectTimer = 2; // seconds
var timerIncrease = 2;
var conn = null;

startWebsocketConnection
();

function startWebsocketConnection() {
conn
= new ab.Session(
'ws://localhost:8080'
, function() { // Once the connection has been established
console
.log("Opened connection");
// set websocketPolling to true and reset reconnect timer
websocketPolling
= true;
websocketReconnectTimer
= 2; // seconds
stopAjaxPolling
(); // stop ajax polling if any

conn
.subscribe('some-topic', function(topic, data) {
// handle data
});
}
, function() { // When the connection is closed or do not exist
console
.warn('WebSocket connection closed');
startAjaxPolling
();

startReconnectingWebsocketConnection
();
}
, {
'skipSubprotocolCheck': true
}
);
}

function AjaxPolling() {
if(!ajaxPolling) { // if ajaxPolling is false, go out ;)
stopAjaxPolling
();
return;
}

$
.ajax({
url
: '/get-data',
type
: 'GET',
dataType
: 'JSON',
success
: function(data) {
// handle data

// set timeout to make another ajax request
ajaxPollingTimeout
= setTimeout(function() {
AjaxPolling();
}, ajaxPollingTimer * 1000);
}
});
}

function startReconnectingWebsocketConnection() {
websocketPolling
= false;
// set timer, it will call startWebsocketConnection() method for 4s, 8s, 16s, 32s, ...
websocketReconnectTimer
= websocketReconnectTimer * timerIncrease;
setTimeout
(function() {
startWebsocketConnection
();
}, websocketReconnectTimer * 1000);
}

function startAjaxPolling() {
if(!ajaxPolling) {
ajaxPolling
= true;
AjaxPolling();
}
}

function stopAjaxPolling() {
ajaxPolling
= false;
if(ajaxPollingTimeout)
clearTimeout
(ajaxPollingTimeout);
}