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");
CodePudding user response:
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>
CodePudding user response:
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>