Right way to dynamically update table - javascript

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:
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.

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.

Related

How to create a function to be re-used for later within another function

I got this code:
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
if(selectedSlots.length < 1 ||$("#positionAppliedFor").get(0).value.length < 1 ||$("#maxAmountOfHours").get(0).value.length < 1){
//error messages and array
var errorForSlots= "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
var errors = [];
//add errors to array
if(selectedSlots.length < 1){errors.push(errorForSlots)};
if($("#positionAppliedFor").get(0).value.length < 1){errors.push(errorForPosition)};
if($("#maxAmountOfHours").get(0).value.length < 1){errors.push(errorForHours)};
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if($("#sectionError").length > 0){$("#sectionError").remove()};
}
console.log("function finished");
}));
It all works perfectly, however, I am trying to figure out how to create a function for
//create message
var div = "<div id=\"sectionError\">";
if($("#sectionError").length > 0){$("#sectionError").html('')};
$(div).appendTo($(this).get(0).parentNode);
for(var i = 0; i < errors.length; i++){
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);}
$("</div>").appendTo($(this).get(0).parentNode);
I am planning to re-use this for few other sections on my form and rather than copy/paste I would like to get some help on making my code tidier.
I did try:
function myFunction(){
//message code here
}
$(document).ready(function(){
$(".nextForm").on('click',(function(){
//check criteria
...
//add errors
...
//call func
myFunction();
(I also tried this.myFunction();)
...
}));
});
However, that ended up in TypeError and I don't know where to begin...
I am also concerned about the "this" in my message code so I am also not sure how to address that in my new function...
Admitedly I am a newbie at this and I do not exactly understand all the ins and outs, hopefully you will be able to help.
Maybe there is a better way of doing this?
Let me know your thought either way!
Thanks.
I have created a small reusable framework same as how jQuery is doing behind the scene to expose reusable functions. I didn't tested the append function properly,I just explaining how you can create your own reusable plugin to reuse across the project.
You can change the parameters and method name that you want to expose based on your functionality.
Also I would suggest you to move this code to a javascript file as a plugin and drag after the jquery script.
(function (global, $) {
//you can pass the jQuery object in to this IIFE
var DisplayError = function (elementId) {
return new DisplayError.init(elementId);
}
DisplayError.prototype = {
appendError: function (errors) {
var div = "<div id=\"" + this.elementId + " \">";
if ($(this.elementId).length > 0) {
$(this.elementId).html('')
};
$(div).appendTo($(this.elementId).get(0).parentNode);
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($(this.elementId));
}
$("</div>").appendTo($(this.elementId).get(0).parentNode);
}
};
DisplayError.init = function (elementId) {
var self = this;
self.elementId = elementId;
}
DisplayError.init.prototype = DisplayError.prototype;
global.DisplayError = global.DisplayError = DisplayError;
}(window, jQuery));
You can write the code for clear the html directly in init function to ensure the element is clearing while initialize the instance itself.
You can invoke the method like below ,
var displayError=DisplayError("#sectionError")
displayError.appendError(["errorId"])
or
DisplayError("#sectionError").appendError(["errorId"])
Hope this helps
New Function
function generateMessage(arg1) {
//create message for each section
console.log("generating message");
var div = "<div id=\"sectionError\">";
if ($("#sectionError").length > 0) {
$("#sectionError").html('')
}
;$(div).appendTo($(arg1).parent());
for (var i = 0; i < errors.length; i++) {
$(errors[i]).appendTo($("#sectionError"));
console.log(errors[i]);
}
$("</div>").appendTo($(arg1).parent());
}
Changed old function
$(document).ready(function() {
$("#adbutnext").on('click', (function() {
//check criteria
if (selectedSlots.length < 1 || $("#positionAppliedFor").get(0).value.length < 1 || $("#maxAmountOfHours").get(0).value.length < 1) {
//error messages and array
var errorForSlots = "<h5>Select at least one availability slot</h5>";
var errorForPosition = "<h5>Enter the position you wish to apply for<h5>";
var errorForHours = "<h5>Enter the amount of hours you would like to work<h5>";
errors = [];
//add errors to array
if (selectedSlots.length < 1) {
errors.push(errorForSlots)
}
;if ($("#positionAppliedFor").get(0).value.length < 1) {
errors.push(errorForPosition)
}
;if ($("#maxAmountOfHours").get(0).value.length < 1) {
errors.push(errorForHours)
}
;
generateMessage(this);
} else {
$("#applicationDetails").slideUp();
$("#personalDetails").slideDown();
if ($("#sectionError").length > 0) {
$("#sectionError").remove()
}
;
}
console.log("function finished");
}
));
});

How to update Firebase multiple times

so when trying to go through a loop that checks, updates, and posts data to my Firebase storage, it seems that whenever I try to use the Firebase.update(), then it messes with my for loop and it repeats incrementations or doesn't increment at all. Any advice?
My Code:
var j = 0;
var k = 0;
var l = 0;
var m = 0;
var setDict = {};
for(var h = 0; h < teamWinNames.length; h++)
{
console.log(j);
console.log(h);
console.log(meWinList[j]);
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
var tempName = teamWinNames[h];
tempRef.once("value", function (teamWinSnapshot)
{
var exists = teamWinSnapshot.child(meWinList[j] + '/' + tempName).exists();
console.log(exists);
if(exists == true)
{
console.log("Here");
var tempVal = teamWinSnapshot.child(meWinList[j] + '/' + tempName).val();
console.log(tempVal);
//var tempValue = obj[tempname][tempchamp];
//console.log(tempValue);
}
else
{
setDict[tempName] = '1-0-0-0';
console.log(setDict);
}
});
if(h != 0 && (h+1)%4 == 0)
{
sendUpdate(setDict, meWinList[j], username);
setDict = {};
j++;
}
}
and the function that makes the update:
function sendUpdate(data, champ, username)
{
var tempRef = new Firebase("https://mycounter-app.firebaseio.com/user/" + username + "/championData");
tempRef.child(champ).update(data);
}
The problem is that you are getting your data in the for loop and also changing it inside the loop. This means that the data you are using in your loop changes with each iteration. And as an added bonus you get the effects of the asynchronous nature of firebase that can look something like this:
Get data (1)
Get data (2)
Update data (1)
Get data (3)
Update data (3)
Update data (2)
To prevent all this i suggest putting the for loop inside the tempRef.once function like this: (pseudo code)
tempRef.once{
Loop through data{
Change data
}
Update data
}
This means you only have to get the data once and update it once.

jsonp request does not show facebook data

I am using JSON to display info from a site. The book example works which gave me a custom website to get information from worked, but when I replaced the url with Spider man's facebook page, it seems as if the data is processing, but the information does not display. Is there some crucial step that I am missing.
var lastReporttime = 0;
window.onload= function(){
setInterval(handleRefresh,3000);
}
function updateSales(sales) {
var salesDiv= document.getElementById("sales");
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) { lastReporttime = sales[sales.length-1].time; }
}
function handleRefresh() {
var url = "http://graph.facebook.com/SpiderManDVD"
+ "callback=updateSales"
+ "&lastreporttime=" + lastReporttime
+ "&random="+ (new Date()). getTime();
var newScriptElement= document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement= document.getElementById("jsonp");
var head= document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
Response you received from your book example returns a JSON Array which is perfectly handled in your code.
But response from facebook api returns a JSON object which is breaking your code.
Check both the urls and update the logic inside updateSales to handle both JSON Array as well as JSONObject as per your use case.
Something like this
function updateSales(sales) {
var salesDiv= document.getElementById('sales');
// Check if sales is array or not (One of the crude ways, ofcourse not best but may work for you)
if (typeof sales.length == 'undefined') {
sales = [sales];
}
for (var i = 0; i < sales.length; i++) {
var sale = sales[i];
var div = document.createElement("div");
div.innerHTML = sale.category + sale.about + "spiderman";
salesDiv.appendChild(div);
}
if (sales.length > 0) {
lastReporttime = sales[sales.length-1].time;
}
}

Create dynamic elements in javascript and visualize it on UI as soon as the node is created

I am working on a script that creates a tree. The problem i am facing is when large chunk of data comes it gets stuck for some time then rendering every thing at the end.
What i am looking for is can there be a way that make it more interactive. Like as soon as a node is being made it gets popup at the Interface.
For getting into the inside i am posting my code.
function recursiveGenerateTree(objNode, parntSpan, ulContainer, objEditParam) {
var cntLi = 0;
var spnApplyClass;
var rdbValue;
var cntrList = 0;
for (cntLi = 0; cntLi <= objNode.NodeList.length - 1; cntLi++) {
objEditParam.rdbGroup = objEditParam.rdbGroup;
rdbValue = objEditParam.orgRootID + '_' + objNode.NodeList[cntLi].Id;
objEditParam.rdbValue = rdbValue;
objEditParam.selector = 'radio';
objEditParam.selector = '';
objEditParam.isNewNode = false;
addChild('', parntSpan, ulContainer, objEditParam);
$('#txtParent').val(objNode.NodeList[cntLi].Name);
spnApplyClass = $('#txtParent').parents('span:first');
$('#txtParent').trigger('blur', [spnApplyClass]);
spnApplyClass.removeClass('bgLime');
var li = spnApplyClass.parents("li:first");
li.attr("nodeId", objNode.NodeList[cntLi].Id);
li.attr("rootnodeId", objNode.NodeList[cntLi].RootOrgUnitId);
var ulPrsnt = objNode.NodeList[cntLi].NodeList;
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);
}
}
}
Second function used is Add child
function addChild(currentbtn, parentSpn, parentUl, objEditParam) {
var spnElement;
if ($(currentbtn).length > 0) {
var dvClick = $(currentbtn).closest('div').siblings('div.OrgGroupLists')
spnElement = $(dvClick).find('span.bgLime');
}
else {
spnElement = parentSpn;
}
if (spnElement.length == 0 && parentUl.length == 0)
return;
var crtUlChild;
if (spnElement.length > 0) {
var dvCurrent = $(spnElement).closest("div");
crtUlChild = $(dvCurrent).find('ul:first');
}
if (parentUl.length > 0) {
crtUlChild = parentUl;
}
if (crtUlChild.length == 0) {
var ulChildrens = createUl();
}
//Next line needs to be updated.
var spnImage = $(dvCurrent).find("span:first");
$(spnImage).removeClass("SpanSpace");
$(spnImage).addClass("L7CollapseTree");
var liChildrens = document.createElement("li");
$(liChildrens).attr("isNew", objEditParam.isNewNode);
$(liChildrens).attr("isTextEdited", false);
var dvChildrens = createDivNode(objEditParam);
$(liChildrens).append(dvChildrens);
if (crtUlChild.length == 0) {
$(ulChildrens).append(liChildrens);
$(dvCurrent).append(ulChildrens);
}
else {
crtUlChild.append(liChildrens);
}
}
Feel free to ask any more details if required to understand the problem more clearly.
What #nnnnnn means is that you call subsequent recursion in setTimeout.
I did not spend time trying to replicate your code locally. Check out JavaScript code below for example. setTimeout works fine for the code below. You can vary variable j's length according to your browser. The inner loop j is to block JS thread.
<html><head>
<script>
var k = 0;
function recursiveTree(){
$("#holder").append("<div>Item</div>");
for(var j =0; j < 100000000; j++){
// blocking thread
}
if (k++ < 20) {
console.log(k);
setTimeout(function(){recursiveTree()},10);
}
}</script>
</head>
<body>
<div id='holder'></div></body>
</html>
I assumed that you are using JQuery.
Just to confirm you need to make recursive call as following
if (ulPrsnt != undefined && ulPrsnt.length > 0) {
setTimeout(function(){recursiveGenerateTree(objNode.NodeList[cntLi], spnApplyClass, '', objEditParam);},10);
}

Client side javascript, creation of several elements and show each asap

Client side javascript code creates some elements (about 50-100) in a cycle:
for (var i = 0; i < list.length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
}
There are some problems with browser rendering. For example, IE just freezes until it finishes the cycle, and then shows all elements at once. Is there a way to show each created element separately and immediately after appendChild()?
This is due to the single threaded nature of browsers. Rendering will not begin until the thread becomes idle. In this case, it's when your loop has completed and the function exits. The only way around this is to (sort of) simulate multiple threads using timers, like so:
var timer,
i = 0,
max = list.length;
timer = window.setInterval(function ()
{
if (i < max)
{
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
mainObj.appendChild(obj);
i++;
}
else
window.clearInterval(timer);
}, 1);
The obvious drawback is that this will take your loop longer to complete because it's fitting the rendering inbetween each iteration.
insert a delay between adding successive entries, with setTimeout().
function insertEntry(list, ix) {
if (ix == null) {
ix = 0;
}
else if (ix < list.length) {
var elt= document.createElement("DIV");
var attr = document.createAttribute('id');
attr.value = 'item'+ix;
elt.setAttributeNode(attr);
elt.innerHTML = "<span class='itemCls'>" + list[ix].Id + ': ' + list[ix].Name +
"</span><!-- some more simple code -->\n";
mainObj.appendChild(elt);
ix++;
}
if (ix < list.length) {
setTimeout(function(){insertEntry(list, ix);}, 20);
}
}
Kick it off with:
insertEntry(myList);
where myList is like this:
var myList = [
{ Id : '1938377', Name : 'Sven'},
{ Id : '1398737', Name : 'Walt'},
{ Id : '9137387', Name : 'Edie'}
...
};
demo: http://jsbin.com/ehogo/4
I wold do it like this using jQuery instead:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
timer = window.setInterval(function ()
{
for (var i = 0; i < 100; i++) {
$('#container').append('<div>testing</div><br />');
}
},10);
});
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
jQuery does it so quickly, you won't even need to bother about showing as they are created, but you can make it smoother by adding a timer as the example shows.
Is there a specific reason you want the DOM to be updated after every cycle?
It would be alot faster if you create all the elements in one javascript element, and add this one element to the DOM when the cycle is finished.
var holder = document.createElement("DIV");
for (var i = 0; i < list.Length; i++) {
var obj = document.createElement("DIV");
obj.innerHTML = "<span class=\"itemId\">" + list[i].Id
+ "</span><!-- some more simple code --> ";
holder.appendChild(obj);
}
mainObj.appendChild(holder);

Categories

Resources