Reputation: 5089
I have an AJAX chat application that constantly gets new data and appends it to a div (#container) in the form of another div (.child). Multiple .child's can be inserted per second, but I only want to keep the most recent 10. Every time a download occurs, I call the following function:
function cleanup(){
var current = $('#container');
var allData = current.children();
if(allData.length > 10){
for(var i = 0;i<allData.length-10;i++){
allData[i].remove();
}
}
}
This works, but it lags horrendously. I have to switch my current tab just to see the css work correctly. Am I doing something wrong?
I cannot change the data flow, as the chat depends on getting all the data that is sent. I am just looking for the most efficient way of deleting old elements.
Example:
If I had 30 children in my div, the first 20 children would be .remove()
'd and only the last 10 would remain.
Upvotes: 0
Views: 61
Reputation: 82241
You can use :lt()
selector to limit to target last divs( as :lt selector is zero index based):
$('#container .child:lt('+$('.child').length-11+')').remove();
also its better to replace the content rather than appending new one.
Upvotes: 1
Reputation: 2064
CSS Solution:
#container:nth-of-type(10) ~ #container {
display: none;
}
Upvotes: 0
Reputation: 6620
Rather than letting some code add divs and the cleanup function clean it up afterwards - which if I understand you correctly, could add a whole bunch of children, not just one - why not have effectively a queue of length 10 in memory, and keep pushing things on (and popping them off the back once you reach 10+ items), and then set those children on your #container periodically.
This way you are always going to get the latest 10 elements, but you can update the container at a rate that makes sense (and therefore reflow the visual document a a rate that makes sense).
This could be on an interval, or you could even do it every time you process a message - but the point is, you are not adding to the document, reflowing it, then removing from it again. That seems like an inefficient way to approach the problem.
Upvotes: 4