Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 800
NXT Avatar asked Apr 24 '10 17:04

NXT


People also ask

What happens when a function calls itself?

When a function calls itself, that's called a recursion step. The basis of recursion is function arguments that make the task so simple that the function does not make further calls. A recursively-defined data structure is a data structure that can be defined using itself.

What is the use of jQuery callback function?

jQuery Callback FunctionsJavaScript statements are executed line by line. However, with effects, the next line of code can be run even though the effect is not finished. This can create errors. To prevent this, you can create a callback function.

When function calls to itself again and again is called?

A function is called a recursive function if it calls itself again and again . Recursion can be direct as well as indirect.


1 Answers

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

like image 145
sjobe Avatar answered Sep 29 '22 08:09

sjobe