如何在间隔中显示数组索引的值

时间:2018-03-19 20:10:02

标签: javascript jquery settimeout

小提琴:https://jsfiddle.net/uafaLstf/1/

我有以下内容:

$(".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>

我要做的是每1秒后显示一次名称...但是在我的代码中,每个条目都会立即显示整个列表。

我认为我非常接近并且遗漏了一些东西。有人可以帮助我的代码......

2 个答案:

答案 0 :(得分:1)

你可以做的是在函数中传递class Ui_mainWindow(object): def setupUi(self, mainWindow): ... self.toolBar.addAction(self.new_item_entry) self.toolBar.addAction(self.exiting_item) self.toolBar.addAction(self.item_edit_name) self.toolBar.addAction(self.action_9) ... def retranslateUi(self, mainWindow): ... import resrcs class MainWindow(QtGui.QMainWindow, Ui_mainWindow): def __init__(self, *args, **kwargs): QtGui.QMainWindow.__init__(self, *args, **kwargs) self.setupUi(self) self.new_item_entry.triggered.connect(self.on_new_item_entry) self.exiting_item.triggered.connect(self.on_exiting_item) self.item_edit_name.connect(self.on_item_edit_name) self.action_9.triggered.connect(self.on_action_9) def on_new_item_entry(self): # some code def on_exiting_item(self): # some code def on_item_edit_name(self): # some code def on_action_9(self): # some code if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) app.setLayoutDirection(QtCore.Qt.RightToLeft) app.setStyle('Plastique') w = MainWindow() w.show() sys.exit(app.exec_()) 的值然后用它来计算setTimeout的延迟

f
$(".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);
}

答案 1 :(得分:1)

你根本不需要for-loop。只需触发setTimeout三次(或点燃setInterval并在3次后重置)。

附注:

1)优化:无需拨打arr.push三次,您可以在一次通话中执行此操作

2)您可以使用$(".span1").append()来缩短代码。

$(".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);
}