递归闭包在JavaScript [英] Recursive closures in JavaScript
问题描述
假设我有像
function animate(param)
调用的局部变量也可以立即释放。
{
//。 ..
if(param< 10)
setTimeout(function(){animate(param + 1)},100);
}
animate(0);这意味着函数的本地数据的每个实例都将保存在内存中,直到animate完成,例如,直到(a)到(b)。 param达到10?
如果实例保存在内存中,是否有更好的方法?我知道,传递文本代码到
setTimeout()
解决了这个问题,但在我的情况下,函数参数之间的对象不能很容易地表示为字符串解决方案不,函数的本地数据的最多两个实例将在任何给定的时间点保存在内存中。这是事件的顺序:
animate(0)
/ li>
- 创建了
param == 0
的关闭,现在可以阻止此变量的释放。
- 超时触发,
animate(1)
被呼叫。
- 新的关闭与
param == 1
,它现在阻止此变量被释放。
- 第一个闭包完成执行,此时它不再被引用并可以释放。 $ <$ c $>> animate()
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.
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.- A closure with
param == 0
is created, it now prevents this variable from being released. - Timeout fires,
animate(1)
is called. - New closure with
param == 1
is created, it now prevent this variable from being released. - 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. - Repeat starting with step 3, now with
animate(2)
.
这篇关于递归闭包在JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!