How to stop the interval after changing all three messages?

I need to stop the interval after changing all messages but I can’t. Can you help me? Thanks.

<script>
$(document).ready(function(){
    var textos = ["Hi", "Fine?", "0"];
    var atual = 0;
    $('#display').text(textos[atual++]);
    setInterval(function() {
        $('#display').fadeOut(function() {
            if (atual >= textos.length) atual = 0;
            $('#display').text(textos[atual++]).fadeIn();
        });
    }, 10);
});
</script>

>Solution :

use for loop? or put this in a var and cleat when needed

<script>
    $(document).ready(function(){
        var textos = ["Hi", "Fine?", "0"];
        var atual = 0;
      // here
        var intervalId;
        $('#display').text(textos[atual++]);
        intervalId = setInterval(function() {
            $('#display').fadeOut(function() {
                if (atual >= textos.length) {
            // clear
                    clearInterval(intervalId);
                } else {
                    $('#display').text(textos[atual++]).fadeIn();
                }
            });
        }, 1000);
    });
</script>

to keep last one try this

$(document).ready(function(){
    var textos = ["Hi", "Fine?", "0"];
    var atual = 0;
    var intervalId;

    $('#display').text(textos[atual++]);
    intervalId = setInterval(function() {
        if (atual >= textos.length - 1) {
            clearInterval(intervalId);
        } else {
            $('#display').fadeOut(function() {
                $('#display').text(textos[atual++]).fadeIn();
            });
        }
    }, 1000);
});

Leave a Reply