Fadein delay and attenuation

I am trying to create a list of objects and repeat their attenuation. However, each time the page loads, it jumps to "Last Text". I assume that he is doing something asynchronous and has just flashed through the list, because the console is displaying all the values. Every solution I find ends with the same result.

Here is what I still have:

$(document).ready(function(){
  var resumation = [
    {value: "First Text", type: "text", top: 340, duration: 5},
    {value: "Second Text", type: "text", top: 340, duration: 5},
    {value: "Last Text", type: "text", top: 340, duration: 5}
  ];
  $("#ab-text").fadeOut(0);
  $.each(resumation, function(index, obj){
    console.log(obj.value);
    $("#ab-text").empty().append(obj.value).fadeIn(5000, function(){
      $("#ab-text").delay(3000).fadeOut(5000, function(){
        return;
      });
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ab-text"></div>
Run codeHide result
+4
source share
1 answer

An issue with your code is that it $.eachdoes not expect anything. It looks through all the elements at once, as you will see on the console using the instructions .log. This means that it ab-textwill be set to all different values ​​almost immediately, stopping at the last element.

- . , , , each.

- , next .

$(document).ready(function(){
  var resumation = [
    {value: "First Text", type: "text", top: 340, duration: 5},
    {value: "Second Text", type: "text", top: 340, duration: 5},
    {value: "Last Text", type: "text", top: 340, duration: 5}
  ];

  next(0);

  function next (i) {
    var obj = resumation[i % resumation.length];
    $("#ab-text").empty().append(obj.value).fadeIn(5000, function () {
      $("#ab-text").delay(3000).fadeOut(5000, function(){
        next(i + 1);
      });
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ab-text"></div>
Hide result
+6

Source: https://habr.com/ru/post/1691039/


All Articles