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

146
Views
Función de efecto de escritura de JavaScript

Estoy tratando de escribir una función JS que tome un argumento, txt y lo imprima letra por letra, ya tengo un código, pero cuando intento 'convertirlo' como una función, deja de funcionar. ¿Algunas 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();

Función de efecto de escritura:

 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 answers
Answer question

0

Debe pasar el texto original a la función en setTimeout , así como eliminar el bucle sobre todo el texto que está llamando en cada devolución de llamada de setTimeout (lo que hace que imprima el texto completo en cada devolución de llamada).

Como mejora, también sugeriría pasar el índice en las llamadas a funciones.

 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 Report

0

Es más fácil con promesas y 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 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!