I have got a WebSocket client running, that gets the streams of data from the Binance WebSocket API. The client accesses the stream and updates a Datatable with the stream data. But due to the big amount of data being updated to the table, it has made the DataTable very slow. And due to the amount of memory being used by the WebSocket it causes the page to reload if it is left open for too long
let trackedStreams = [];
var table = $('#example').DataTable( {
columns: [
{ title: "Pair", data: "pair" },
{ title: "Last Price", data: "lprice" },
{ title: "24h Change", data: "24change" },
{ title: "24h High", data: "24high" },
{ title: "24h Low", data: "24low" }
]
});
let ws = new WebSocket("wss://stream.binance.com:9443/ws/!ticker@arr");
ws.onopen = function() {
console.log("Binance connected...");
};
ws.onmessage = function(evt) {
try {
let msgs = JSON.parse(evt.data);
if (Array.isArray(msgs)) {
for (let msg of msgs) {
handleMessage(msg);
}
} else {
handleMessage(msgs)
}
} catch (e) {
console.log('Unknown message: ', e);
}
}
ws.onclose = function() {
console.log("Binance disconnected");
}
function handleMessage(msg) {
const stream = msg.s;
if (trackedStreams.indexOf(stream) === -1) {
//if symbol doesnt exist in array
var tmpArray = [msg.s, msg.c, msg.P, msg.h, msg.l];
trackedStreams.push(stream);
table.rows.add([ {
"pair": msg.s,
"lprice": msg.c,
"24change": msg.P,
"24high": msg.h,
"24low": msg.l
} ])
.draw()
.nodes()
.to$()
.addClass( msg.s );
} else {
var selectedRow = table.rows('.' + msg.s);
console.log(selectedRow);
table.row( selectedRow ).data( {
"pair": msg.s,
"lprice": msg.c,
"24change": msg.P,
"24high": msg.h,
"24low": msg.l
} ).draw();
}
My question is, is there a better approach to this method to make it more efficient, to make the DataTables more responsive and to make sure the WebSocket is not using too much memory?