向Jquery.each添加定时延迟

时间:2017-05-29 14:03:37

标签: jquery arrays each settimeout delay

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

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

IdTache

4 个答案:

答案 0 :(得分:2)

您可以创建一个计数器并使用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>

答案 1 :(得分:0)

使用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

答案 2 :(得分:0)

只需使用索引进行超时。中间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();

答案 3 :(得分:0)

如果不添加新变量来计算迭代次数,只需使用index param

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();