1

我的 setInterval 代码第一次运行良好,但没有正确重复——在第一次之后,它在第一个实例和第二个实例之间没有延迟。这是我的代码还是 setInterval 的问题?

    setInterval(function() {

        $('#img2').fadeIn(500).delay(5000).fadeOut(500);

    }, 5000);

为了澄清(如果我的代码真的很糟糕!)我希望我的 img 在 5 秒后淡入,在那里停留 5 秒,然后淡出 - 5 秒后淡入,停留 5 秒,淡出;重复。

编辑:为了进一步澄清,我想我需要问:有没有办法在设置间隔时解释函数的延迟?现在我的间隔与函数内的延迟同时发生,它导致间隔之间的时间为 0。

谢谢大家!

4

5 回答 5

4

setInterval() just starts the function on a repeating time schedule, it doesn't base the repetitions on how long each one takes. Use setTimeout to schedule the restart a fixed time after each one ends.

function delay_and_fade() {
    setTimeout(function() {
        $('#img2').fadeIn(500).delay(5000).fadeOut(500);
        delay_and_fade();
    }, 5000);
}

delay_and_fade();
于 2013-08-27T04:52:35.957 回答
1

尝试使用它。

setInterval(function() {
$('#img2').fadeIn(500);
$('#img2').delay(5000);
$('#img2').fadeOut(500);
}, 5000);
于 2013-08-27T04:43:39.893 回答
1

演示

setInterval(function() {
  $('img').fadeIn(500).delay(500).fadeOut(500);
}, 500);
于 2013-08-27T04:47:12.613 回答
0

你在这里有两个不同的问题。

  1. 您希望您的淡入/淡出动画在 5 秒延迟后开始。
  2. 您希望动画在完成 5 秒后重新开始。

让你的动画每 5 秒重复一次:

function fadeAnimation() {
    $('#img2').fadeIn(500).delay(5000).fadeOut(500);
    // this executes immediately, so add 500+5000+500 (6000) to the time
    // to account for the animation time
    setTimeout(fadeAnimation, 5000 + 6000);
}

要将动画设置为在 5 秒后开始:

setTimeout(fadeAnimation, 5000);

那有意义吗?

于 2013-08-27T05:37:37.147 回答
0

thanks for the responses! I was able to fix it by changing my code to this:

    setInterval(function() {

        $('#img2').fadeIn(500).delay(5000).fadeOut(500).delay(5000);

    }, 5000);

By adding a delay after my fadeout it keeps 5 seconds between each interval and it has a 5 second delay at the start! Just what I was wanting :-)

于 2013-08-27T04:53:03.837 回答