简体   繁体   中英

JQuery Closure Memory Leak

I have done some research ( JavaScript closure and memory issues ), but don't fully understand JS closures and how they affect memory leaks. I'm doing more research as I'm asking this question to try to understand it better, but thought I'd see if anyone can look at this and diagnose the problem while I do.

I am using jQuery on my website to update data in a table. It slowly creeps up in memory as it's being used, but the biggest problem is when a user refreshes the page, it jumps by ~3MB. Similar problems happen when open other tabs in the browser, to the point that after a few hours of use it could be using 200MB of memory. Through my reading, I think I've narrowed the problem to a closure issue in my code. Here's the primary part doing most of the work.

$(document).ready(function(){
setDateSelect();
var url_fm_smry=url_fm_smry_base + url_fm_currdate2 + url_region;
$.getJSON(url_fm_smry,function(data)
{
    $('#summaryContainer').empty();
    $('#summaryTblTmpl')                 // Select the template.
    .tmpl(data.d.results)               // Bind it to the data.
    .appendTo('#summaryContainer');     // Render the output.
});

$.getJSON(url_fm_meta + url_region,function(data)
{
    $('#runDTM').empty();
    $('#runDTMTmpl')                     // Select the template.
    .tmpl(data.d.results)               // Bind it to the data.
    .appendTo('#runDTM');               // Render the output.
});

setInterval(summaryCall,5000);});

setDateSelect loads a drop-down menu with variable dates based on today's date.

url_fm_smry is a local variable composed of 3 global variables that other functions need access to.

summaryCall just does the exact thing as above, repeating every 5 seconds to update the table with a new stream of data.

Thanks for any suggestions and help.

Internally, getJSON does this:

getJSON: function( url, data, callback ) { 
    return jQuery.get( url, data, callback, "json" );
}

Set a breakpoint at this line and view the Function scopes. There is at least:

  1. jQuery
  2. jQuery.getJSON callback
  3. jQuery.get internal call
  4. jQuery.get internal callback

Call jQuery.get directly with a named function rather than an anonymous function to avoid the closure scope.

References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM