Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive closures in JavaScript

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.

like image 986
mojuba Avatar asked Aug 11 '11 09:08

mojuba


People also ask

What are the closures in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

What is recursive method in JavaScript?

Recursion is a process of calling itself. A function that calls itself is called a recursive function. The syntax for recursive function is: function recurse() { // function code recurse(); // function code } recurse();

Can you do recursive functions in JavaScript?

Introduction to the JavaScript recursive functionsThe recurse() is a recursive function if it calls itself inside its body, like this: function recurse() { // ... recurse(); // ... } Generally, you use recursive functions to break down a big problem into smaller ones.

What are the disadvantages of closures in JavaScript?

There are two main disadvantages of overusing closures: The variables declared inside a closure are not garbage collected. Too many closures can slow down your application. This is actually caused by duplication of code in the memory.


1 Answers

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).
like image 128
Wladimir Palant Avatar answered Sep 28 '22 08:09

Wladimir Palant