为 Jquery.each 添加时间延迟

Adding a timing delay to Jquery.each

我想通过 jQuery.each 函数 运行 这个数组,并在每次迭代之间添加一个延迟,在附加到 div 的每个单词之间创建一个停顿.我已经看到使用 setTimeout 回答了其他类似的问题,但我一直没有成功地将其应用到我的代码中。

https://jsfiddle.net/samseurynck/7xw9ujjh/2/

var arr = ["one ", "two ", "three ", "four ", "five "];

function myFunction() {
  jQuery.each(arr, function(index, value) {
    $(".testBox").append('<p class="box">' + value + '</p>');
    console.log('yes');
  });
}

myFunction();

您可以创建一个计数器并使用 setTimeout() 方法:

var arr = ["one ", "two ", "three ", "four ", "five "];

function myFunction() {
  var count = 0;
  jQuery.each(arr, function(index, value) {

    setTimeout(function() {
      $(".testBox").append('<p class="box">' + value + '</p>');
      console.log('yes');
    }, count * 1000)
    count++;
  });
}

myFunction();
.testbox {
  height: 100%;
  width: 100%;
  position: absolute;
}

p {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testBox">
  <p class="box">

  </p>
</div>

使用index增加setTimeout()

的延迟计时器
var arr = ["one ", "two ", "three ", "four ", "five "];

function myFunction() {
  var $box = $(".testBox"),// cache container to avoid dom search each iteration
    delay = 500; //time in ms

  jQuery.each(arr, function(index, value) {
    setTimeout(function() {
      $box.append('<p class="box">' + value + '</p>');
      console.log('yes');
    }, index * delay)

  });
}

myFunction();

fiddle demo

只使用索引超时。中间间隔 1 秒的示例:

var arr = ["one ", "two ", "three ", "four ", "five "];

function myFunction() {
  jQuery.each(arr, function(index, value) {
    setTimeout(function(){
        $(".testBox").append('<p class="box">' + value + '</p>');
        console.log('yes');
    }, index*1000)
  });
}

myFunction();

无需添加新变量来计算迭代次数,只需使用 index 参数

var arr = ["one ", "two ", "three ", "four ", "five "];

function myFunction() {
 jQuery.each(function(index, value) {
    setTimeout(function() {
      $(".testBox").append('<p class="box">' + value + '</p>');
      console.log('yes');
    }, 1000 * index)
  });
}

myFunction();