Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

86
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda