Empty spaces are ignored by the InnerText property

Don’t use presentation as data. Store the current content as a separate string, don’t pull it from the DOM. This way you’re not dependent on how the browser stores the element’s text content.

const text = ["H", "e", "l", "l", "o", " ", "h", "o", "w", " ", "a", "r", "e", "y", "o", "u", "?"]
const parag = document.getElementById("theParagraph");

function typeText() {
  var i = 0;
  var paragText = "";
  var interval = setInterval(function() {
    paragText += text[i];
    parag.innerText = paragText;
    i++;
    if (text.length == i)
      clearInterval(interval);
  }, 200)
}
<body>
  <p id="theParagraph"></p>
  <button id="typeButton" onclick="typeText()" style="padding:15px">Start typing the sentence</button>
</body>

As a side note, the same thing could be made a lot simpler:

const text = "Hello how are you?";
const parag = document.getElementById("theParagraph");
function typeText() {
    var i = 0;
    var interval = setInterval(function () {
        parag.innerText = text.substr(0, i);
        if (text.length == i)
            clearInterval(interval);
        i++;
    }, 200)
}
<body>
    <p id="theParagraph"></p>
    <button id="typeButton" onclick="typeText()" style="padding:15px">Start typing the sentence</button>
</body>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)