我不确定如何提出现在在我脑海中盘旋的问题,所以请耐心等待。我是异步编程的新手,我认为最好的学习方法是制作一个小的 javascript 乒乓球游戏。我从一个 shootball() 函数开始,只是在另一个 div 周围弹跳一个 div。我是如何做到这一点的:
function shootball(angle, speed){
angle = (angle/360.0)*2*Math.PI;
var ballmotion = setInterval(function(){
var nowx, nowy, minusY, plusX;
nowx = $("#ball").position().left;
nowy = $("#ball").position().top;
minusY = Math.sin(angle) * 4.0;
plusX = Math.cos(angle) * 4.0;
if(hitsWall(nowx+plusX, nowy-minusY)){
clearInterval(ballMotion);
shootball(newAngle(nowx+plusX, nowy-minusY), speed);
}
$("#ball").css("left", (nowx + plusX)).css("top", (nowy - minusY));
}, 10/speed);
}
我不是大型不必要递归的忠实拥护者,但我只是想尝试一下。瞧,它的工作原理与我预期的完全一样。但是当我开始充实程序的其余部分时,我突然想到我无法避免这种递归性质。所以我的问题是:javascript 是否以某种方式识别调用 clearInterval 后调用的“shootball”函数基本上完成了?或者这是否真的发现自己用不必要的激活记录加载了我的堆栈?在此先感谢您提供的任何专业知识。
最佳答案
Does javascript somehow recognize that the calling "shootball" function is essentially finished after calling clearInterval?
不,shootball
很久以前就完成了,就在分配给 ballmotion
之后。然而,它的变量作用域(angle
、speed
、ballmotion
和父作用域)确实存在,因为匿名函数用它构建了一个闭包并且是从外部(从调度程序)引用。在删除了对它的引用的 clearInterval
调用之后,该作用域将被垃圾收集。
does this really find itself loading up my stack with unnecessary activation records?
没有。通过 setTimeout
/setInterval
执行的每个函数都在其自己的执行上下文中运行,并带有全新的调用堆栈。
关于javascript - 异步 Javascript 递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17090292/