简体   繁体   English

某些 setInterval + jQuery FadeIn/FadeOut 出现问题

[英]Having problems with some setInterval + jQuery FadeIn/FadeOut

I'm trying to fade in / out some text inside a div.我正在尝试淡入/淡出 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在 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.然后再次启动计时器。

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.然后在fadeIn 中创建一个递归回调,当它完成时启动计时器。

Updated fiddle: http://jsfiddle.net/ZCadu/2/ .更新小提琴: http : //jsfiddle.net/ZCadu/2/

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();
});
​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM