Javascript每个循环,暂停不暂停

时间:2019-02-23 18:34:40

标签: javascript html

我正在尝试获取此简单脚本,以将关键字值附加到div innerhtml。但是我希望它在每次打印之间停顿一下。这是到目前为止我得到的。现在,它只是一次不停地转储所有内容,或者仅打印数组中的最后一个元素。不知道我在做什么错。

var root_keywords = [
  "Keyword 1",
  "Keyword 2",
  "Keyword 3",
  "Keyword 4"
];

document.getElementById("genBtn").addEventListener("click", createKeywords);
var kwDiv = document.getElementById("output");

function createKeywords()
{  
  root_keywords.forEach(function(kw)
  {
    var OldContents = kwDiv.innerHTML;
    var NewContents = OldContents + kw + "<br />";
    doAppend( NewContents );
  });
}

function doAppend(kw) {
  var kwDiv = document.getElementById("output");
  setTimeout(function() { kwDiv.innerHTML = kw }, 500);
}
#output{
  padding:10px;
  width: 200px;
  height: 200px;
  background-color:#000;
  display:block;
  color:#66a565;
}
<!DOCTYPE html>
<html>
<head>
<title>Keyword Generator</title>
</head>
<body>

<h1>This is a Heading</h1>
 <button type="button" id="genBtn">Generate</button>
  <div id="output"></div>

</body>
</html> 

1 个答案:

答案 0 :(得分:4)

将超时毫秒数乘以您要迭代的当前索引,否则每个超时将立即激活:

var root_keywords = [
  "Keyword 1",
  "Keyword 2",
  "Keyword 3",
  "Keyword 4"
];

document.getElementById("genBtn").addEventListener("click", createKeywords);
var kwDiv = document.getElementById("output");

function createKeywords() {
  root_keywords.forEach(function(kw, i) {
    var OldContents = kwDiv.innerHTML;
    var NewContents = OldContents + kw + "<br />";
    doAppend(NewContents, i);
  });
}

function doAppend(kw, i) {
  var kwDiv = document.getElementById("output");
  setTimeout(function() {
    kwDiv.innerHTML = kw
  }, 500 * i);
}
#output {
  padding: 10px;
  width: 200px;
  height: 200px;
  background-color: #000;
  display: block;
  color: #66a565;
}
<h1>This is a Heading</h1>
<button type="button" id="genBtn">Generate</button>
<div id="output"></div>