JQuery setInterval with append, increase memory

2019-08-15 07:11发布

问题:

Sorry for my bad English.

I've created a chat system with jQuery and when i try to replace contents(like users online-offline or messages recived) it works perfectly but start to be more and more slowly, cause javascript start to take more and more the memory.

$(document).ready(function(e) {
data = '<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>';

$("body").empty().append(data);

setInterval(function(){
    $("body").empty().append(data);
    }, 1000);

}); //document

Testing in Google Chrome (I can't post images here cause I'm new). Appears in Timeline Memory more and more, and Nodes(green line) creasing as stairs to, all the time.

I've tested with:

document.getElementById("selector_inthiscasetheidofthebody").innerHTML="";

and then

document.getElementById("selector_inthiscasetheidofthebody").innerHTML=data;
  • I've used setTimeout method insted of setInterval

  • I've tried with html() jQuery method

This is the image:

Any other ideas? Thanks.

回答1:

I've found it! You can't avoid increasing memory and nodes but you can control them! This is the code:

    $(document).ready(function(e) {

// Possible data    
data = '<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>';

// Clean all that browsers changes, like putting styles inline, etc. Data and html appened, must be the same
function clean(a){
    if((a != 'undefined') && (a != null)){
    a = a.replace(/(\ style=".*?")/gi,'').replace(/(<tbody>)/gi,'').replace(/(<\/tbody>)/gi,'').replace(/(\&amp\;)/gi,'&').replace(/(\&lt\;)/gi,'<').replace(/(\&gt\;)/gi,'>').replace(/(\")/gi,"'");
    return a.trim();
    }
    };

// If they are different, then append data. So, you only append data in case information changes.
function inyectar(a,b){
    if(clean($(a).html()) != clean(b)){
        $(a).empty().append(b);
        }
    }

setInterval(function(){
    inyectar("body",data);
        }, 1000);
});