0

How to show a div for 2 seconds and then hide it for 4 seconds in an infinite loop? I use jQuery's animate() function because I want to use CSS transitions too.

function animatedText() {
    setTimeout(function() {
        $('.text').animate({ opacity: 1 }, 200, function() {
            setTimeout(function() { 
                $('.text').animate({ opacity: 0 }, 200);
            }, 1800);
        });
    }, 3800);
}
setInterval(animatedText(), 6000);

Here is my fiddle : https://jsfiddle.net/od6gm8t3/

  • 2
    Your `setInterval` does not run anything because the call of `animatedText` does not return anything. If `animatedText` should be called every 6 seconds then you need to write `setInterval(animatedText, 6000)`. Instead of using intervals and timeouts you should use the `delay` functionality of jQuery and the finish callback of the animation. – t.niese Jun 14 '17 at 16:40
  • I see. Thank you! –  Jun 14 '17 at 17:10

1 Answers1

0

I hope this will help you. Please check below code.

function animatedText() {
    $('.text').animate({ opacity: 1 }, 200, function() {
            setTimeout(function() { 
                $('.text').animate({ opacity: 0 }, 200);
            }, 2000);
    });
    setTimeout(function() {
        animatedText();
    },6000);
}
animatedText();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<i class="text">Animated Text</i>
Alex Mac
  • 2,970
  • 1
  • 22
  • 39
  • Thank you! This is almost what I need. The problem is that it will show the div as soon as I call the function. I mean it doesn't wait for 4 seconds but I think I can call the function inside a setTimeout function on window load. Right? –  Jun 14 '17 at 17:07
  • Can you please show me your code, so I can help you better. – Alex Mac Jun 14 '17 at 17:09
  • I mean this : https://jsfiddle.net/od6gm8t3/1/ Is there a better way to do it inside the function? Your code shows the div as soon as the function called –  Jun 14 '17 at 17:18
  • I think this is the only way to achieve this. Because your requirement is display after 4 seconds than stay for 2 seconds and this will contiue infinite. – Alex Mac Jun 14 '17 at 18:21