0

Fiddle: https://jsfiddle.net/uafaLstf/1/

I have the following:

$(".span1").html("Warm Welcome To: " + "<br />");
arr = [];

arr.push(["john", "jdoe", "very nice"]);
arr.push(["mike", "mdone", "job well"]);
arr.push(["haan", "hgore", "creative"]);

var interval = 1000;
for (var f = 0; f < arr.length; f++) {
    SendWishes(arr[f][0]);
}

function SendWishes(name) {
    setTimeout(function () { $(".span1").html($(".span1").html() + name + "<br />"); }, 1000);
}

<span class="span1"></span>

What I am trying to do is display the name after every 1 second... however in my code the entire list is displayed without delay for each entry.

I think I am pretty close and missing something. Can someone please help with my code...

Si8
  • 9,141
  • 22
  • 109
  • 221

2 Answers2

1

What you can do is pass the value of f in the function and then use it to calculate the delay of setTimeout

$(".span1").html("Warm Welcome To: " + "<br />");
arr = [];

arr.push(["john", "jdoe", "very nice"]);
arr.push(["mike", "mdone", "job well"]);
arr.push(["haan", "hgore", "creative"]);

var interval = 1000;
for (var f = 0; f < arr.length; f++) {
  SendWishes(arr[f][0], f);
}

function SendWishes(name, f) {
  setTimeout(function() {
    $(".span1").html($(".span1").html() + name + "<br />");
    if (f === arr.length - 1)
      console.log("Loop is over");
  }, 1000 * f);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="span1"></span>
void
  • 36,090
  • 8
  • 62
  • 107
1

You don't even need a for-loop at all. Just fire the setTimeout three times (or fire setInterval and reset it after 3 times).

Side notes:

1) optimisation: no need to call arr.push three times, you could do that in one call

2) you can use $(".span1").append() to shorten the code.

$(".span1").html("Warm Welcome To: " + "<br />");
arr = [];

arr.push(["john", "jdoe", "very nice"],
         ["mike", "mdone", "job well"],
         ["haan", "hgore", "creative"]);

var f = 0;

SendWishes();

function SendWishes() {
    setTimeout(function () {
        $(".span1").append(arr[f++][0] + "<br />"); 
        if(f < 3) SendWishes();
        //OR: if(f < arr.length) in case you plan to push something else to your array
  }, 1000);
}
nicael
  • 18,550
  • 13
  • 57
  • 90