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");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>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>