简体   繁体   中英

Typewriter effect in JS (can't pass my string to the typewriter function)

Currently working on the UI for the first time and I seem to be stuck.

Here's what I'm trying to achieve: text1 is typed out once the page is loaded (with the typewriter effect). Then, when the user clicks a button, text1 immediately disappears and text2 begins to be typed out instead.

My function (in my HTML I have a paragraph with id="demo")

function typeWriter(text,speed) {
  for (let i = 0; i < text.length; i++) {
    document.getElementById("demo").innerHTML += text.charAt(i);
    setTimeout(typeWriter, speed);
  }
}
typeWriter("Lorem impsum", 50);

The problem is that I cannot figure out how to pass my string in the function. The code above returns an error:

"TypeError: undefined is not an object (evaluating 'text.length')".

What could I do about that? How can I get the length if I don't want to have some "fixed" string, since I need to pass in 2 different texts, depending on the events?

Your error : "TypeError: undefined is not an object (evaluating 'text.length')". is caused when you code reached text.length because text is undefined . Now in first iteration it is correct, but after your setTimeout , the callback typeWriter does not have any params.

If you want to pass params to a setTimeout callback, this is the way:

setTimeout(functionRef, delay, param1, param2, /* ... ,*/ paramN)

Now, you can add that but i believe you do not even need a for loop. Because then in every iteration you will have n calls to setTimeout. And every time the callback function itself will call setTimeout.

Doing minor changes to your code, can fix this:

 function typeWriter(text,speed,char) { if(char < text.length){ document.getElementById("demo").innerHTML += text.charAt(char); setTimeout(typeWriter, speed,text,speed,char+1); } } typeWriter("Lorem impsum", 50,0);
 <div id="demo"></div>

In the above sample i am keeping track of the character by passing an index and calling setTimeout exactly once every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM