Surak Surak - 3 months ago 9
Javascript Question

I need a delay that isn't setTimeout()

This is the code that I have and I want to make it so that the letters (sentence parameter) type themselves one by one. Not all at a time. I keep trying with setTimeout() but I can't do it so that it keeps it's progress. Please help.

var letters = [];

function typeOut(sentence, code) {
$('body').append('<p id=' + code + '></p>');


for (i = 0; i < sentence.length; i++) {
letters[i] = sentence[i];
$('#' + code).append(letters[i]);
}
}

typeOut("Hello World", 1);


Thanks in advance!

Answer

setTimeout seems perfect. I guess you are using it incorrectly.

function typeOut(sentence) {
  var txt = document.body
    .appendChild(document.createElement('p'))
    .appendChild(document.createTextNode(''));
  var i = 0;
  (function typeLetter() {
    if(i < sentence.length) {
      txt.nodeValue += sentence[i];
      ++i;
      setTimeout(typeLetter, 100);
    }
  })();
}
typeOut("Hello World");

Comments