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

85
Views
I'm trying to print one letter after another

I'm trying to print one letter after another but this code just waits 100ms and then prints the value with no pauses. Any idea why this happens and how to fix it? Code:

    for (let i = 0; i < welcText.length; i++) {
        setTimeout(()=>{
            welcome.innerText += welcText[i];
        },100);
    }
about 4 years ago ยท Juan Pablo Isaza
3 answers
Answer question

0

Note that setTimeout does not actually delay the running of the code that comes after; it just schedules for something to happen in the future. So all the letters are added at the same time, after 100 milliseconds.

The most straightforward way to fix it is to make each subsequent timeout wait a bit longer, by multiplying the delay with the index of the letter (i * 100):

const welcome = document.getElementById('welcome');
const welcText = 'Welcome!';

for (let i = 0; i < welcText.length; i++) {
    setTimeout(() => {
        welcome.innerText += welcText[i];
    }, i * 100);
}
<div id="welcome"></div>

about 4 years ago ยท Juan Pablo Isaza Report

0

The following function divtxt() returns a Promise. You can use it to send a txt to a div with a given id and let each letter appear in ms intervals. AND: you can build a chain of any number of follow-up actions with it:

function divtxt(id, txt, ms, wait = 0) {
  const div = document.getElementById(id);
  return new Promise((res, rej) => {
    setTimeout(() => { // optional initial timeout, when wait>0
      div.textContent = "";
      const a = txt.split(""),
        iv = setInterval(() => {
          if (a.length)
            div.textContent += a.shift();
          else {
            clearInterval(iv);
            res(txt);
          }
        }, ms);
    }, wait);
  });
}
divtxt("welcome", "Hello world, this is my way of doing it! ๐Ÿคฉ", 100)
  .then(prevText => (console.log(prevText + ' is done.'),
    divtxt("descr", "You can also chain this function with any number of consecutive actions."
    +" Now: wait for 2 seconds ...", 100)))
  .then(() => divtxt("welcome", "This promised-based approach REALLY lets you do it!! ๐Ÿ‘๐Ÿป", 50, 2000))
  .then(() => (console.log("ready?"),"Yes! I am REALLY DONE now! ๐Ÿ˜"))
  .then(console.log)
#welcome {
  font-weight: 900
}
<div id="welcome"></div>
<div id="descr"></div>

about 4 years ago ยท Juan Pablo Isaza Report

0

You can do it using setInterval instead, and using an iterator to call the next char of the string every time. This is a bit more complicated, but has the advantage of not having multiple schedulers running if the string is too long. See the working example below.

const welcome = document.getElementById('welcome');
const welcomeText = 'Welcome!';

// returns a function that returns the next char in the string everytime its called
function createIterator(string) {
  let currentIndex = 0;
  return function() {
    return string[currentIndex++];
  }
}
// initializes the iterator with the text
let welcomeIterator = createIterator(welcomeText);

let welcomeInterval = setInterval(function() {
  let nextChar = welcomeIterator();
  // if we finish the string we clear the interval
  if (!nextChar) {
    return clearInterval(welcomeInterval);
  }
  // if the char exists, we append it to the div
  welcome.innerText += nextChar;
}, 100);
<div id="welcome"></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!