Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

recursion - If a jQuery function calls itself in its completion callback, is that a recursive danger to the stack?

I'm writing a little jQuery component that animates in response to button presses and also should go automatically as well. I was just wondering if this function recursive or not, I can't quite work it out.

function animate_next_internal() {

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

My actual function is more complicated to allow for stops and starts, this is just a simplified example.

EDIT It could either overflow the stack or not, depending on how the events are handled internally. Possibilities:

  1. animate() directy calls the done callback, in which case an overflow is inevitable.

  2. animate() schedules the callback for calling by some external dispatching mechanism and then terminates, in which case it will never overflow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I initially suspected that it would overflow the memory, but I wrote a short test to confirm

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();

and surprisingly, I saw

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

in my logs. Looks like "animate() schedules the callback for calling by some external dispatching mechanism and then terminates, in which case it will never overflow." is the right answer


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...