jQuery append delay

1.2k Views Asked by At

Can someone explain why the rows in the console are appending all in one time? I want them to get append one by one. row is an array of strings in the program and here is the code:

var dodajRed = function(redenBroj) {
    setTimeout(function() {
        $('.console').append('<p>' + row[redenBroj] + '</p>');
    }, 1500);
}

dodajRed(0);
dodajRed(1);
dodajRed(2);

I want the rows to appear one by one with 1500ms delay, but instead I get all rows appeared after 1500ms.

2

There are 2 best solutions below

0
On BEST ANSWER

There are lots of ways to do this. One possible solution is adjust your timeout:

var dodajRed = function(redenBroj){
  setTimeout(function () {
    $('.console').append('<p>'+row[redenBroj]+'</p>');
  }, (redenBroj + 1) * 1500);
}

dodajRed(0);
dodajRed(1);
dodajRed(2);

You could also setup a promise chain, but you'd need an external library or browser that supports ECMAScript 6.

0
On

Try using setInterval instead:

(function() {
  var index = 0,
    row = ["One", "Two", "Three"],
    id,
    stop = function() {
      if (index > 2) {
        clearInterval(id);
      }
    },
    start = function() {
      id = setInterval(function() {
        $('.console').append('<p>' + row[index] + '</p>');
        index++;
        stop();
      }, 1500);
    };
  start();
}());

JSFiddle