Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda