views:

92

answers:

1

So I've recently setup a chrome extension to refresh a page and call a jsonp web service I've written but there is a memory leak. I've searched all of the internet to find solutions and nothing seems to work. I've used the plain jQuery .ajax() call specifying "jsonp", I've used jquery-jsonp found at http://code.google.com/p/jquery-jsonp/, and a slew of other methods...I cannot get the memory leak to disappear. Can someone point me to an example that does what I'm looking for or point me in the right direction? I just need to see a script constantly call a jsonp call and not leak memory.

when running my code there is no leaks until i reach this code:

$.jsonp({
                url: serviceUrl + "/AddPick?callback=?&" + jQuery.param(json),
                success: function (returned, textStatus) {
                    callback({ "d": returned.d, "pickCount": pickCount });
                }
            });

if i replace that code with: callback({ "d": "1", "pickCount": pickCount }); then the leak goes away.

A: 

If your code is structured like this:

function callback() {
  // (or similar, maybe with `setTimeout`)

  $.jsonp({
    url: serviceUrl + "/AddPick?callback=?&" + jQuery.param(json),
    success: function (returned, textStatus) {
      callback({ "d": returned.d, "pickCount": pickCount });
    }
  });
}

Then a new success function is being created recursively. The call stack may look like this:

> callback
  > $.jsonp
    > NEW success
      > callback
        > $.jsonp
          > NEW success
            > ...

The growing stack, the new success functions being created at each iteration, and the entire context of the success functions themselves (which includes returned, textStatus, and callback's context) eventually lead to objects which the runtime must keep track of but are basically unused.

An alternative is to have a helper function outside of the scope of callback:

function callCallback(returned, textStatus) {
  callback({ "d": returned.d, "pickCount": pickCount });
}

function callback() {
  // (or similar, maybe with `setTimeout`)

  $.jsonp({
    url: serviceUrl + "/AddPick?callback=?&" + jQuery.param(json),
    success: callCallback
  });
}

If needed, make the function private. For example:

var callback = (function () {
  function callCallback(returned, textStatus) {
    callback({ "d": returned.d, "pickCount": pickCount });
  }

  function callback() {
    // (or similar, maybe with `setTimeout`)

    $.jsonp({
      url: serviceUrl + "/AddPick?callback=?&" + jQuery.param(json),
      success: callCallback
    });
  }

  return callback;
})();
strager