Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

422
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!