如果jQuery函数在其完成回调中调用自身,那么对堆栈的递归危险是什么?

我正在编写一个小的jQuery组件,它响应按钮按下而动画,也应该自动进行。 我只是想知道这个函数是否递归,我不能完全解决它。

function animate_next_internal() { $('#sc_thumbnails').animate( { top: '-=106' }, 500, function() { animate_next_internal(); } ); } 

我的实际function更复杂, 允许停止和启动,这只是一个简化的例子。

编辑它可能是否溢出堆栈,具体取决于事件在内部处理的方式。 可能性:

  1. animate()directy调用完成的回调,在这种情况下溢出是不可避免的。

  2. animate()调度回调以供某些外部调度机制调用然后终止,在这种情况下它永远不会溢出。

我最初怀疑它会溢出内存,但我写了一个简短的测试来证实

 function test(){ $(".logo img").css("position", "absolute"); $(".logo img").css("top", "100px"); $(".logo img").animate({top:0}, 500, function(){ test(); console.log("exits here"); }); } test(); 

令人惊讶的是,我看到了

 exits here exits here exits here exits here exits here ... 

在我的日志中。 看起来“animate()调度回调以便通过某种外部调度机制进行调用然后终止,在这种情况下它永远不会溢出。” 是正确的答案

我希望这样的实现会溢出调用堆栈。 除非你简化了它,否则你应该有某种终止条件导致函数退出递归。 你可能需要这样的东西:

 function animate_next_internal() { if ( some_condition ) return; $('#sc_thumbnails').animate( { top: '-=106' }, 500, function() { animate_next_internal(); } ); } 

some_condition是与递归相关的东西 – 也许当#sc_thumbnails实际上到达某个限制时,如页面上或其父级内的0。