9

In response to this question about jQuery effects, I thought about using the callback argument to .fadeIn( 500, my_function ).

While in principle, this is a viable idea, I have no clue (and neither has the jQuery documentation :( ) if the callback is allowed to recurse:

function keep_animating(){
   $("#id").fadeIn(500).fadeOut(500, keep_animating );
}
Community
  • 1
  • 1
xtofl
  • 40,723
  • 12
  • 105
  • 192

3 Answers3

3

You could add a debugger breakpoint and test if the stack size increases or not. :)

However, since animations/fadings use setTimeout/setInterval I highly guess that the call depth does not increase, i.e. it's not prone to stack overflows.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • From what I can see in the source, it does recurse. See the [speed function](http://www.keyframesandcode.com/resources/javascript/deconstructed/jquery/#speed), which eventually handles the callback functions from all effects. It uses `call()` to execute the callback directly, there is no queue involved. – Tomalak Feb 18 '11 at 15:17
  • It was the 'guess' in your answer that made me doubt. It was the smiley in your answer that didn't make vote you down. But in the end, you prove to be right (at least, backed up by some blokes at the jQuery forum - check out http://forum.jquery.com/topic/continuation-style-programming-are-there-constraints-on-the-fx-callbacks ) – xtofl Feb 21 '11 at 08:51
1

I took the time to ask the 'people who know'... There is no stack-overflow, since there is no explicit recursion: the fadeIn, fadeOut ... methods all just create an entry on the effects queue. That means that the keep_animating function is not executed from within the same context.

Courtesy to dave methvin:

What you are describing as "recursion" is not actually recursion. jQuery's visual effects run on a setTimeout timer, so the callback function isn't run immediately as it would be in recursion. Instead, the callback runs after the animation completes in several "steps", each triggered by a setTimeout.

xtofl
  • 40,723
  • 12
  • 105
  • 192
0

Your solution will recurse, and eventually blow out the stack-- but you'll have quite a while-- depending on the browser-- until it does. For a quick demo this is fine, but for production ready code you'll want to take a non-recursive approach, such as:

function pulse(){
   $("#id").fadeIn(500).fadeOut(500);
}
setInterval(pulse, 1000);

There are many ways to skin this, but should get you there.

ndp
  • 21,546
  • 5
  • 36
  • 52