开发者

Is continuation-style-programming prone to stack overflow

开发者 https://www.devze.com 2023-02-12 02:40 出处:网络
In response to this question about jQuery effects, I thought about using the callback argument to .fadeIn( 500, my_function ).

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 docum开发者_运维知识库entation :( ) if the callback is allowed to recurse:

function keep_animating(){
   $("#id").fadeIn(500).fadeOut(500, keep_animating );
}


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消