jQuery 附加延迟

jQuery append delay

谁能解释一下为什么控制台中的行一次性全部追加?我想让他们一个一个地追加。 row 是程序中的字符串数组,代码如下:

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

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

我希望使用 1500ms delay 逐行显示,但我让所有行都出现在 1500ms 之后。

有很多方法可以做到这一点。一种可能的解决方案是调整超时:

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

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

您也可以设置承诺链,但您需要一个支持 ECMAScript 6 的外部库或浏览器。

尝试改用 setInterval:

(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