Multiple DOM updates in one redraw / recount?

I have a table that is populated with a list of connected users. The list itself does not change very often, but one of the things on each line is the timer (hh: mm: ss), which is updated every second. To update the timers, I am doing something like this:

var curTime = new Date().getTime() / 1000; $('.timerCell').each(function(){ var $this = $(this); var initialTime = $this.data('sessionStartTimestamp'); // .data gets when the cell is dynamically created based on data received in an ajax request. $this.text(unixToHumanTime(curTime - initialTime)); }); 

The problem I am facing is this: every time one timer cell is updated, it causes a redraw. Is there any way to tell the browser to wait to redraw? or perhaps somehow combine these updates into one update. I also thought about re-rendering the whole body every time an update occurs, but I thought that it would probably be more intensive in the system than just updating the cells.

+4
source share
2 answers

Do not use jQuery for this. Let’s manually make a fragment of the document and add it to the DOM so that we don’t cause a repeat draw.

 var curTime = new Date().getTime() / 1000; $('.timerCell').text(function(){ var elm = $(this).get(0); var frag = document.createDocumentFragment(); elem.removeChild(elem.childNodes[0]); frag.appendChild(document.createTextNode(unixToHumanTime(curTime - initialTime))); elem.appendChild(frag); }); 
+4
source

Try the following:

 var curTime = new Date().getTime() / 1000; $('.timerCell').text(function(){ var initialTime = $(this).data('sessionStartTimestamp'); return unixToHumanTime(curTime - initialTime); }); 

Many jQuery methods allow you to pass a callback function with a return value. Strictly speaking, this code still updates .timerCell one at a time, but does it more efficiently.

+2
source

Source: https://habr.com/ru/post/1387462/


All Articles