jquery/js : best way to have an image fading in and out? (recursion?)
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(40开发者_Python百科0);
recursive_fade();
};
$(function(){
recursive_fade();
});
When i dynatrace this, it seems to use fair bit of cpu...
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.
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();
});
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);
}
精彩评论