0

I'm trying to get this simple script to append the keyword values to the div innerhtml. But I want it to pause in between each print. Here's what I've got so far. Right now, it just dumps either everything all at once without a pause, or prints the last element in the array only. Not sure what I'm doing wrong.

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> 
joeb
  • 777
  • 8
  • 28
  • `setTimeout` doesn’t pause your script when you call it; it just adds a call to today’s schedule. All of the calls are scheduled for 500 ms in the future at more or less the same time. – Ry- Feb 23 '19 at 18:38
  • 1
    gotcha. I thought setTimeout worked like php's sleep(). – joeb Feb 23 '19 at 18:40

1 Answers1

4

Multiply the timeout milliseconds by the current index you're iterating over, else every timeout will activate at once:

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>
Snow
  • 3,820
  • 3
  • 13
  • 39