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

NXT*_*NXT 6 recursion jquery jquery-callback

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

function animate_next_internal() {

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

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

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

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

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

sjo*_*obe 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();
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,我看到了

exits here
exits here
exits here
exits here
exits here
...
Run Code Online (Sandbox Code Playgroud)

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