samseurynck
samseurynck

Reputation: 133

Adding a timing delay to Jquery.each

I'd like to run this array through the jQuery.each function and add a delay in-between each iteration, creating a pause in between each word appending to the div. I've seen other similar questions answered using setTimeout but I have been unsuccessful applying that to my code.

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

Upvotes: 1

Views: 3849

Answers (4)

WilomGfx
WilomGfx

Reputation: 2013

Without adding a new variable to count the iteration, just use the 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();

Upvotes: 0

Slim
Slim

Reputation: 1964

Just use the index for the timeout. Example with 1 second in between:

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

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

Use the index to increment the delay timer for 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

Upvotes: 0

Ionut Necula
Ionut Necula

Reputation: 11480

You can create a counter and use setTimeout() method:

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>

Upvotes: 4

Related Questions