Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Problem with JavaScript code

Hi, I'm trying to type the content of my heading element letter by letter, 100miliseconds each one. Can you tell me why it's not working? Here is my JavaScript code:

const heading = document.querySelector('.heading');
const headingText = 'Meet our Developer Team';
let i = 0;

function typingHeading () {
  for ( i=0; i<headingText.length; i++ ) {
      function typeLetter () {
        heading.innerHTML += headingText.charAt(i);
      }
      setTimeout(typeLetter(), 100)
  }
}

typingHeading();

2 Answers

I was trying to use this stack overflow to get an understanding of how to accomplish this with setTimeout() and a loop but decided it was better to just use setInterval() since that is what it is for.

const heading = document.querySelector('.heading');
const headingText = 'Meet our Developer Team';

function typingHeading () {
  var i = 0
  var id = setInterval(typeLetter, 100);

  function typeLetter () {
     if (i == headingText.length ) {
       clearInterval(id);
     }  else {
       heading.innerHTML += headingText.charAt(i);
       i++
     } 
  }
}

typingHeading(); 

Thank you :)

But I have one more question, you invoked typingHeading function and I don't understand exactly what is happening inside it - I mean that you deaclared typeLetter function and setInterval function inside, but you haven't invoked any of it so how is it running?

Christian Clarke
Christian Clarke
7,963 Points

Kris beat me to the code but basically what was happening is that the setTimeout was holding up your entire loop instead of just the piece of it where you make adjustments to the text. I think that's just the nature of setTimeout. So putting those changes into a setInterval (setInterval runs every specified period of time vs. setTimeout which basically tells your program not to run anything for a specific period of time once) and essentially creating a timed for loop allows everything to run the way you were intending.