0

I'm trying to create a typewriter function for a school project and i'm not sure why its not working

HTML code:

<h1 id="typewriter"></h1>

Javascript code:

typewriter();

function typewriter() {
    var textArray = text1.split("");
    for (var i = 0; i < textArray.length; i++) {
        document.getElementById('typewriter').innerHTML = textArray[i];
        setTimeout(typewriter, 80);
    }
}

Thanks in advance for the help!

doğukan
  • 23,073
  • 13
  • 57
  • 69

4 Answers4

4

I think you're looking for something like this:

You set a timeout for every char of the string, but give every timeout additional delay

So the first char will be written after 0ms delay
The second after 100ms delay
The third after 200ms delay
And so forth

Example:

function typewriter(element, text, delay = 100) {
  for (let i = 0; i < text.length; i++) {
    setTimeout(() => {
      element.innerHTML += text[i];
    }, delay * i);
  }
}

const el = document.getElementById("typewriter");
typewriter(el, "Lorem ipsum dolor sit amet");
<h1 id="typewriter"></h1>
Jannes Carpentier
  • 1,838
  • 1
  • 5
  • 12
2

Using modern async/await makes things like this nice and simple.

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

async function typewriter(element, text, delay = 100) {
  for (let i = 0; i < text.length; i++) {
    await sleep(delay);
    element.innerHTML += text[i];
  }
}

const el = document.getElementById("typewriter");
typewriter(el, "Lorem ipsum dolor sit amet");
<h1 id="typewriter"></h1>
Keith
  • 22,005
  • 2
  • 27
  • 44
0

You need to setInterval to trigger the function multiple times. Set time out it fires just once when the time came

text = text.split("")

function typewriter() {
    document.getElementById('typewriter').innerHTML += text.shift();
}


setInterval(typewriter, 1000);
agentp
  • 335
  • 4
  • 17
  • 1
    You should cancel the interval after it has finished, otherwise it will keep spamming `"undefined"` – FZs Aug 06 '20 at 11:29
0

Use this way it will work.

var i = 0;
var text = "Hello World!!";
typewriter();
function typewriter() {
    debugger;
    if (i < text.length) {
        document.getElementById('typewriter').innerHTML += text.charAt(i);
        i++;
        setTimeout(typewriter, 100);
    }
}
Sagar Kumar
  • 55
  • 1
  • 5