Socket.IO with DataTables
Socket.IO with DataTables
Good day!
I have been testing out DataTables with Socket.IO for the past week.
In my test, I tried doing the following:
1.) Client connects to the server.
2.) If connection is successful, server reads a file, read each line and save them to an array.
* While reading each line, server sends an event ('line') to the client to display the progress of the reading.
3.) Once the reading is done, server sends another event ('complete') with the array (where the lines are stored) to the server and display it in a DataTable.
My question is:
Why are there times that the browser freezes before displaying the list sent by the server? It is pretty intermittent though.
Maybe its my code or something but I may need enlightenment regarding this.
By the way, here are my codes:
<script>
$(function () {
var columns = [{ "title": "No", "width": "10%", "orderable": "true" },
{ "title": "Timestamp", "width": "40%", "orderable": "true" },
{ "title": "info", "width": "25%", "orderable": "true" },
{ "title": "details", "width": "25%", "orderable": "true" }];
$('#infoTable').dataTable({
"retrieve": true,
"ordering": true,
"dom": 'RrtS',
"cellspacing": 0,
"scrollY": "660px",
"processing": true,
"columns": columns,
"deferRender": true,
"paging": true,
"searching": false,
"stateSave": false,
});
dataTable = $('#packetTable').dataTable();
$('#infoTable tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
dataTable.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
$(function () {
$("#progressbar").progressbar({
value: false
});
});
});
var counter = 0;
var list = [];
var socket = io.connect();
var dataTable;
var dateNow;
socket.on('connect', function () {
$('#incomingChatMessages').append($('<li>Connected</li>'));
socket.emit('start');
});
socket.on('line', function (packet) {
counter++;
if (!dateNow) {
dateNow = Date.now();
}
var progress = $.fn.dataTable.util.throttle(
function () {
$('#progress').text(counter);
},
100
);
progress();
});
socket.on('complete', function (data) {
console.log(((Date.now() - dateNow) / 1000) + " sec");
dataTable.api().rows.add(data).draw();
dateNow = undefined;
});
socket.on('disconnect', function () {
$('#incomingChatMessages').append('<li>Disconnected</li>');
dataTable.api().clear().draw();
counter = 0;
});
</script>
Answers
Without a test case it is impossible to say.
I would suggest using the profiling tools in your browser's developer tools to see what is happening.
Allan
thank you for that quick response!
apparently, as I tried to check things (had to do it manually), it turned out that when Websockets are used, the code above works like a charm and no lagging occurs. However, when an xhr connection is used for transporting my data (since Socket.IO starts off with an xhr connection before upgrading to a webscoket), the browser lags until before displaying the data.