Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

425
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda