Append div with interval in Jquery

廉价感情. 提交于 2019-12-04 21:39:59

I've done it using two interval()... But one function.

And use some variables to control iterations and delays (or speed).

Look how it slows when it reaches 300.

$(document).ready(function(){

  var intervalSpeed = 20  // in milliseconds
  var ratio_1=1;          // 1 is 100% of the above delay
  var ratio_2=10;  

  var animateSpeed=300;  // in milliseconds

  var i=0;
  
  function twoSpeedInterval(){
    // Append.
    $(".wrapper").prepend("<div class='item' id='" + i + "'>" + i + "</div>");

    // Animate.
    $("#" + i).animate({opacity: 1},animateSpeed);

    // Condition to slow or stop.
    if (i==300){
      clearInterval(interval_1);  // Stop the 1st interval.
      
      // Start 2nd interval.
      interval_2 = setInterval(twoSpeedInterval,intervalSpeed*ratio_2);
      
      animateSpeed = animateSpeed*ratio_2;
    }
    if (i==500){
      clearInterval(interval_2);  // Stop the 2nd interval.
    }

    i++;
  }
  
  // Start 1st interval.
  var interval_1 = setInterval(twoSpeedInterval,intervalSpeed*ratio_1);
  
  var interval_2;
});
.item{
  opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="wrapper"></div>

Just having a bit fun with it, I used jQuery .queue() for this and made i a global variable.

var i = 0;
$(document).ready(function() {
  for (i = 0; i <= 300; i++) {
    $(".wrapper").append("<div class='item' id='" + i + "'>" + i + "</div>");
  }
  for (j = 300; j <= 500; j++) {
    $(".wrapper").delay(1000).queue(function(next) {
      $(this).append("<div class='item' id='" + i + "'>" + i + "</div>");
      i++;
      next();
    });
  }
});
var step = 0;

function hideItemFunc() {
  var interval = setInterval(function() {
    $("#" + step).animate({
      opacity: 1
    }, 50);
    step += 1;
  }, 50);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wrapper"></div>

As commented before,

You will have to use recursion with timer to add delay in loops.

You can check this JSFiddle as a sample or use following snippet to debug:

Note: Please note the difference in the delay for every value where count%3 === 0.

var count = 0;

function animate(delay) {
  setTimeout(function() {
  	var div = $('<div class="tile" style="display: none">'+count+'</div>');
    $('.content').append(div)
    div.fadeIn()

    if (++count < 10) {
      animate(count % 3 === 0 ? 3000 : 1000)
    }
  }, delay || 1000)
}
animate();
.tile {
  height: 40px;
  margin: 5px;
  border: 2px solid #ddd;
  border-radius: 4px;
  background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="content"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!