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.
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.
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();
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.
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.
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:
animate(0)
is called.param == 0
is created, it now prevents this variable from being released.animate(1)
is called.param == 1
is created, it now prevent this variable from being released.animate()
call can also be released now.animate(2)
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With