首页 > 解决方案 > Javascript每个循环都有暂停而不是暂停

问题描述

我试图让这个简单的脚本将关键字值附加到 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> 

标签: javascripthtml

解决方案


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

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>


推荐阅读