Alex Rivera | Logout

Recursive closures in JavaScript

Asked 2011-08-11T09:18:43.497
36

Let's say I have something like

function animate(param)
{
    // ...
    if (param < 10)
        setTimeout(function () { animate(param + 1) }, 100);
}

animate(0);

Does this mean each instance of the function's local data will be held in memory until animate completes, i.e. until param reaches 10?

If it's true that instances are held in memory, is there a better way of doing this? I know, passing textual code to setTimeout() solves the problem but in my case there are objects among function arguments that can't be represented as strings easily.

Edit
Report

1 Answer

13

No, at most two instances of function's local data will be held in memory at any given point in time. Here is the order of events:

  1. animate(0) is called.
  2. A closure with param == 0 is created, it now prevents this variable from being released.
  3. Timeout fires, animate(1) is called.
  4. New closure with param == 1 is created, it now prevent this variable from being released.
  5. The first closure finishes executing, at this point it is no longer referenced and can be released. The local variables from the first animate() call can also be released now.
  6. Repeat starting with step 3, now with animate(2).
answered 2011-08-11T09:27:19.270

Your Answer