1

Is there a better way than this, for two images positioned over each other where #state_2 is the top image.

function recursive_fade(){
    $('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
    recursive_fade();                
};

$(function(){
    recursive_fade(); 
});

When i dynatrace this, it seems to use fair bit of cpu...

Haroldo
  • 36,607
  • 46
  • 127
  • 169

3 Answers3

4

You should use continuation-style here: let the fx system call the recursive_fade when the last animation has finished:

function recursive_fade(){
    $('#top_img')
         .delay(4000)
         .fadeOut(400)
         .delay(4000)
         .fadeIn(400, recursive_fade );
};

EDIT 2 - meanwhile, it seems (long liveth the jQuery forum) that the Effects are implemented using a queue and the setTimeout function - making EDIT 1 obsolete.

EDIT - since I have no idea if jQuery allows this recursion (I didn't find convincing proof), I think it's best to combine the "Timeout" suggestions with the continuation technique like so:

function recursive_fade(){
    $('#top_img')
         .delay(4000)
         .fadeOut(400)
         .delay(4000)
         .fadeIn(400, function() { setTimeout( recursive_fade, 0 ); } );
};

This offers the guarantee that stack won't blow up, yet avoids the need to calculate the timeout interval.

xtofl
  • 40,723
  • 12
  • 105
  • 192
  • So will making the recursive function a callback save CPU? I thought all jquery animations were syncrous? – Haroldo Feb 25 '11 at 11:31
  • The callback is, as you say, going to be called from a timer. It's not going to call itself, rather _schedule_ a call at the moment the effects are done. And, as I mentioned indirectly, the jQuery effects are _asynchronous_. – xtofl Feb 25 '11 at 12:10
0

I wouldn't do it recursively, I would use a setTimeout so it doesnt totally lock up the browser.

function recursive_fade(){
    $('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
    setTimeout(function(){recursive_fade(); },8800);               
};

$(function(){
   recursive_fade();
});
Loktar
  • 34,764
  • 7
  • 90
  • 104
  • and on every change in the fx timings, you need to update the timeout argument. – xtofl Feb 18 '11 at 18:05
  • ... Loktar - I've been asking around. There is no risk to lock up the browser since the effects functions already use timers. – xtofl Feb 21 '11 at 08:52
0

How about using setInterval(). Info here.

Something like this:

function fadeShow() {
    $('#top_img').delay(4000).fadeOut(400).delay(4000).fadeIn(400);
}
$(function() {
    setInterval(fadeShow, 8800);
}
  • 1
    This way you have e tight coupling between the arguments of the whole animation sequence, and your timeout interval. I would rather use `setTimeout` in the `callback` of the `fadeIn`. – xtofl Feb 18 '11 at 15:05