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

147
Visualizações
JavaScript Typing Effect Function

I'm trying to write a JS function that takes one argument, txt and prints it letter by letter, I already have a code, but when I try to 'convert' it as a function it stops working. Any ideas?

var myText = "Text to be displayed";    
var myArray = myText.split("");    
var loopTimer;

function frameLooper() {    
    if(myArray.length > 0) {    
        document.getElementById("type_text").innerHTML += myArray.shift();    
    } else {
        clearTimeout(loopTimer);
        return false;
    }
    loopTimer = setTimeout("frameLooper()",70);
}
frameLooper();

Typing effect function:

var i;
var speed = 120;

function typeWriter(txt) {
  for (i=0;i<=txt.length - 1;i++)
  {
    document.getElementById("type_text").innerHTML += txt.charAt(i);
    setTimeout(typeWriter, speed);
  }
}
typeWriter("text to be typed");
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to pass the original text to the function in setTimeout, as well as remove the loop over the entire text, that you are calling in each setTimeout callback (which makes it print the entire text in each callback).

As an enhancement, I would suggest passing the index in the function calls as well.

const SPEED = 120;

function typeWriter(txt, i = 0) {
  document.getElementById("type_text").innerHTML += txt.charAt(i);
  
  // check if the entire text has been typed
  if (i < txt.length - 1) {
    // pass function with the text and the index (+1)
    setTimeout(() => typeWriter(txt, i + 1), SPEED);
  }
}
typeWriter("text to be typed");
<p id="type_text"></p>

about 4 years ago · Juan Pablo Isaza Relatório

0

It's easier with promises and async:

let delay = n => new Promise(r => setTimeout(r, n));

async function typeWriter(div, txt) {
  for (let char of txt) {
    div.innerHTML += char;
    await delay(200);
  }
}

typeWriter(document.querySelector('#type'), 'hello there')
  
<div id="type"></div>

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