Reputation: 87007
I'm trying to fade in / out some text inside a div. I've kept the time really quick for debugging purposes. The problem is that I think the fade in and outs are fighting each other. Sometimes the text is updated and then it fades in/out.
See this interactive example on JS Fiddle
Here's the code :
var tips = [
'AAA',
'BBB',
'CCC'
];
var currentTipIndex = 0;
setInterval(function () {
currentTipIndex++;
if (currentTipIndex >= tips.length) {
currentTipIndex = 0;
}
$("#pewpew").fadeOut(1000);
$("#pewpew").html(tips[currentTipIndex]);
$("#pewpew").fadeIn(1000);
}, 1 * 5 * 1000);
It's like want the interval timer to stop. then fade out. (wait for fade to finish). update text. fade in. (wait for fade in to start). Then start timer again.
Upvotes: 0
Views: 1933
Reputation: 816
Update:
// Rotating Tips.
var tips = ['AAA', 'BBB', 'CCC'];
var currentTipIndex = 0;
function recursiveTimeout() {
setTimeout(function () {
currentTipIndex++;
if (currentTipIndex >= tips.length) {
currentTipIndex = 0;
}
$("#pewpew").fadeOut(1000, function () {
$("#pewpew").html(tips[currentTipIndex]);
});
$("#pewpew").fadeIn(1000, recursiveTimeout());
}, 1 * 5 * 1000);
};
recursiveTimeout();
Using the fadeOut callback ensures that the animation has finished before loading the content. Then creating a recursive callback within the fadeIn, starts the timer when it's completed.
Updated fiddle: http://jsfiddle.net/ZCadu/2/ .
Upvotes: 2
Reputation: 3524
Try this,
var tips = [
'AAA',
'BBB',
'CCC'
];
function fadeIn(html) {
$("#pewpew").html(html);
$("#pewpew").fadeIn(1000, function() {
$("#pewpew").fadeOut(1000, getNextTip);
});
}
var currentTipIndex = 0;
function getNextTip() {
if (currentTipIndex >= tips.length)
currentTipIndex = 0;
var cTip = tips[currentTipIndex];
fadeIn(cTip);
currentTipIndex++;
}
$(function() {
getNextTip();
});
Upvotes: 0