Creating a closure for .setTimeout() inside a for loop
<p>I am trying to write a javascript program which stores the value from an input element in an array when a button is clicked. The array is the split and each individual letter added to a span element and then appended to the document. The idea is to create a typing effect using setTimeout. </p>

<p>I am running into an issue creating a closure within the loop, so currently the setTimeout function always returns the final value of the iteration.</p>

<p>The function in question is at the bottom of the code block and called addTextToBoard();</p>

<pre><code>var noteButton = document.querySelector('[data-js="button"]');

noteButton.addEventListener("click",function() {
  var messageIn = document.querySelector('[data-js="input"]');
  var message = messageIn.value;
  postToBoard(message);
});

function postToBoard(val) {
  var noteBoard = document.querySelector('[data-js="noteboard"]');
  var newElement = document.createElement('div');
  newElement.classList.add('noteboard__item');
  noteBoard.appendChild(newElement);
  setTimeout(function(){
    newElement.classList.add('active');
  }, 200);
  addTextToBoard(newElement, val);
}

function addTextToBoard(el, val) {
   var wordArray = val.split('');
   for(i = 0; i &lt; wordArray.length; i++) {
       var letter = document.createElement('span');
       letter.innerHTML = wordArray[i];
       setTimeout(function(x){
         return function() {}
         el.appendChild(letter);
       }(i),1000);
   }
}
</code></pre>

<p>I believe I am close, I'm just not fully understanding the syntax for creating the closure. If someone could give poke in the right direction, without necessarily giving the full solution that would be great.</p>

<p>I essentially tried to paste in the following code snippet from <a href="http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside" rel="nofollow">here</a> but I've missed something somehwere along the way!</p>

<pre><code>setTimeout(function(x) { return function() { console.log(x); }; }(i), 1000*i);
</code></pre>

<p>Best,</p>

<p>Jack</p>