0

I have this code which is only doing what i want with last element of my array...why is it so?

    $(document).ready(function () {
        var miArray=["Diseño web multidioma","Desarrollo de aplicaciones","Programacion servidores"];

        for (i = 0; i <3; i++) {



            $("#animation").hide().text(miArray[i]).fadeIn(2000, function () {
                //$(this).css({"background-color": "yellow"}, function(){
                //var div = $("#anuncio");
                alert("the value of miArray[i] is: " + miArray[i]);
                $(this).css({"background-color": "yellow"});
                $(this).animate({height: '160px', opacity: '0.8'}, "slow");
                $(this).animate({width: '300px', opacity: '0.8',}, "slow");
                $(this).animate({height: '160px', opacity: '0.8'}, "slow");
                /* /!*$(this).animate({width: '100px',opacity: '0.8' }, "slow");*!/*/
                $(this).fadeOut(2000)

            });

        }
    });

1 Answers1

0

.fadeIn() and .animation() are asynchronous procedures which for loop does not await the completion of, see JavaScript closure inside loops – simple practical example. You can substitute using $.map(), .queue(), .dequeue(), .promise() and .then() for for loop to await the completion of one or more asynchronous tasks before executing the next function in queueName array.

$(document).ready(function() {
var miArray = ["Diseño web multidioma", "Desarrollo de aplicaciones", "Programacion servidores"];

$("#animation")
.queue("animation"
, $.map(miArray, function(value) {
      // `next` is the next function in `queue` named `"animation"`
      return function(next) {
        return $("#animation")
          .hide()
          .text(value)
          .fadeIn(2000, function() {
            $(this).css({
              "background-color": "yellow"
            })
            .animate({
              height: '160px',
              opacity: '0.8'
            }, "slow")
            .promise()
            .then(function() {
              return $(this).animate({
                width: '300px',
                opacity: '0.8',
              }, "slow").promise()
          })
          .then(function() {
            return $(this).animate({
              height: '160px',
              opacity: '0.8'
            }, "slow").promise()
          })
          .then(function() {
            // call `next` function in `"animation"` queue at `.fadeOut()` callback
            $(this).fadeOut(2000, next) 
          })
      })
  }
}))
.dequeue("animation")
.promise("animation")
.then(function() {
  console.log("done")
})
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div id="animation"></div>
guest271314
  • 1
  • 15
  • 104
  • 177