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

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

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 Report

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