Amandeep Singh
Amandeep Singh

Reputation: 1431

Right way to dynamically update table

I am getting data over websocket every 10 seconds and i am updating the cells using this function:

agentStatSocket.onmessage = function (e) {
  data = JSON.parse(e.data);
  //console.log(typeof(data));

  for (var i = 0; i < data.length; i++) {
    var inboundTd = '#' + data[i]['id'] + '-inbound';
    var outboundTd = '#' + data[i]['id'] + '-outbound';

    if (data[i]['inboundCalls'] != 0) {
      $(inboundTd).html(data[i]['inboundCalls']);
    }

    if (data[i]['outboundCalls'] != 0) {
      $(outboundTd).html(data[i]['outboundCalls']);
    }
  }
};

This is working pretty fine. However, I see some lag with the table being updated. Currently, there are only 150 rows in the table. I do not know what will be the latency if rows will become 1000 or more.

I have the following questions:

  1. What is the correct approach to design these kinds of tables in which data is changing very frequently? I am not using any library like react or angular. This is plain jQuery.I am using dataTables jQuery to enhance table view.

Upvotes: 0

Views: 691

Answers (1)

ATD
ATD

Reputation: 1364

One thing to consider is that, in many cases, accessing an element based on an ID is usually a lot quicker in vanilla javascript compared to jquery.

A simple example of that is:

function jsTest() {
  for (let i = 0; i < 1000; i++) {
    document.getElementById("js").innerHTML = i;
  }
}

function jqueryTest() {
  for (let i = 0; i < 1000; i++) {
    $("#jquery").html(i);
  }
}

function startup() {
  console.time("javascript");
  jsTest();
  console.timeEnd("javascript");
  console.time("jquery");
  jqueryTest();
  console.timeEnd("jquery");
}
// For testing purposes only
window.onload = startup;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript: <div id="js"></div>
Jquery: <div id="jquery"></div>

So, you could try changing your code to:

agentStatSocket.onmessage = function (e) {
  data = JSON.parse(e.data);
  //console.log(typeof(data));

  for (var i = 0; i < data.length; i++) {
    //var inboundTd = '#' + data[i]['id'] + '-inbound';
    //var outboundTd = '#' + data[i]['id'] + '-outbound';
    var inboundTd = data[i]['id'] + '-inbound';
    var outboundTd = data[i]['id'] + '-outbound';

    if (data[i]['inboundCalls'] != 0) {
      //$(inboundTd).html(data[i]['inboundCalls']);
      document.getElementById(inboundTd).innerHTML = data[i]['inboundCalls'];
    }

    if (data[i]['outboundCalls'] != 0) {
      //$(outboundTd).html(data[i]['outboundCalls']);
      document.getElementById(outboundTd).innerHTML = data[i]['outboundCalls'];
    }
  }
};

You can still use jquery for the rest of your code, if you wish, but simple updates to elements that can be targeted by ID are usually quicker with vanilla javascript.

Upvotes: 1

Related Questions