6

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

function animate_next_internal() {

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

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

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

  1. animate() 直接调用 done 回调,这种情况下溢出是不可避免的。

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

4

2 回答 2

9

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

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() 安排回调以通过某些外部调度机制调用然后终止,在这种情况下它永远不会溢出。” 是正确的答案

于 2010-04-25T01:42:03.973 回答
0

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

function animate_next_internal() {

  if ( some_condition ) return;

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

其中some_condition与递归有关——也许当 # sc_thumbnails实际顶部达到某个限制时,例如页面上或其父级中的 0。

于 2010-04-24T23:46:15.770 回答