How to get typewriter to loop?

Issue

I want to figure out how to get the typewriter to loop infinitely with a subtle delay. Currently, it only triggers on page load.

<!DOCTYPE html>
<html>
<body>

<h1>Typewriter</h1>


<p id="demo"></p>

<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}
  window.onload = typeWriter;
</script>

</body>
</html>

Solution

Using setTimeout: reset the paragraph back to "" at the begging. When the length of the text is reached inside the loop, reset i to 0. To add a delay simply use a different speed if it’s the last character.

But, it’s better to use setInterval in your case instead, here is an example:

<h1>Typewriter</h1>

<p id="demo"></p>

<script>
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;

var elem = document.getElementById('demo');

function typeWriter() {
  var i = 0;
  elem.textContent = "";

  var interval = setInterval(function(){
    elem.textContent += txt[i];
    i++;

    if (i === txt.length) {
      clearInterval(interval);
      setTimeout(typeWriter, 3000);
    }
  }, speed)
}

window.onload = typeWriter;
</script>

As @Scott Marcus suggested in the comments, use textContent instead of innerHTML when you’re only changing the text.

Answered By – Enve

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.