0

When referencing a parent variable in a setInterval, do this can provoke a leak as I'm referencing self ?

var A = {};

A.act = function(a_var) {
   var self = this;

   self.a_var = a_var;
   setInterval(function() {
      console.log(self.a_var);
   }, 100)
}

A.act();
Unitech
  • 5,781
  • 5
  • 40
  • 47
  • Nope, that shouldn't be an issue, but it does probably delay garbage collection of the outer function until the interval is cleared. – adeneo Aug 11 '14 at 09:27
  • A leak of *what*? (Other than "memory.") That is, which part is it that you're thinking would stick around when it shouldn't? – T.J. Crowder Aug 11 '14 at 09:38

1 Answers1

1

Well, there's a leak in the sense that you start an interval timer running that you cannot stop without leaving the page (since you don't keep the handle). That means that the context of the call to act that created the timer, the timer callback, and A can never be GC'd, because the browser has a reference to the callback in its timer list, and the callback closes over the context of the call that created it. But I'm assuming that's desired behavior, so not really a leak.

In theory, the a_var argument is referenced by the closure (indirectly, by referencing the binding object of the execution context of the call to act), and so sticks around in memory even though you don't use it (you use self.a_var instead).

In practice (which is to say, allowing for implementation optimizations), it's complicated. Modern engines can optimize out variables and such that they know a closure doesn't access, but surprisingly simple things can disturb that process (at least on V8). This other question and answer have more on that.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875