Websocket com suporte para Ajax Polling

Eu tinha a tarefa de mostrar algumas atualizações de dados em tempo real, e decidi usar websockets. Assim que implementei websockets, decidi ir um pouco mais além e adicionar um suporte Ajax Polling para navegadores que não têm suporte 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);
}