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

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

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 Denunciar

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 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