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

孤街浪徒 提交于 2019-11-29 10:47:05
sjobe

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

I would expect that such an implementation will overflow the call stack. Unless you simplified it out, you should have some kind of terminal condition that causes the function to back out of the recursion. You probably need something like this:

function animate_next_internal() {

  if ( some_condition ) return;

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

Where some_condition is something related to the recursion -- maybe when #sc_thumbnails actual top reaches some limit like 0 on the page or within its parent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!