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

125
Visualizações
how to use setTimeout on a function in javascript

I am trying to create a typing effect using javascript however the text is not readable because it's too fast. I really need a way to make my function pause in every sentence.

const texts = ["get a quote", "get a Tweet"];
let count = 0;
let index = 0;
let currentText = "";
let letter = "";

function type() {
  if (count === texts.length) {
    count = 0;
  }
  currentText = texts[count];
  letter = currentText.slice(0, ++index);

  document.getElementById("welcome").textContent = letter;
  if (letter.length === currentText.length) {
    count++;
    index = 0;
  }

  setTimeout(type, 100)

};
type()
<div id="welcome"></div>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could use a variable for the delay and use a larger one when changing sentences

const texts = ["get a quote", "get a Tweet"];
let count = 0;
let index = 0;
let currentText = "";
let letter = "";

function type() {
  let delay = 100; // default delay between typing chars
  if (count === texts.length) {
    count = 0;
  }
  currentText = texts[count];
  letter = currentText.slice(0, ++index);

  document.getElementById("welcome").textContent = letter;
  if (letter.length === currentText.length) {
    count++;
    index = 0;
    delay = 1000; // larger delay between sentences
  }

  setTimeout(type, delay); // use the delay variable here instead of hardcoding a value

};
type()
<div id="welcome"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

you can try this instead, it gives a different delay to the setTimeout function in the case of a new sentence:

      const texts = ["get a quote", "get a Tweet"];
      let count = 0;
      let index = 0;
      let currentText = "";
      let letter = "";

      function type() {
        if (count === texts.length) {
          count = 0;
        }
        currentText = texts[count];
        letter = currentText.slice(0, ++index);

        document.getElementById("welcome").textContent = letter;
        if (letter.length === currentText.length) {
          count++;
          index = 0;
          setTimeout(type, 1000);
        } else {
          setTimeout(type, 100);
        }
      }
      type();
about 4 years ago · Juan Pablo Isaza Relatório

0

Here's a slightly modified version of your code that doesn't require any global variables, and introduces a two second pause between each line of text.

It uses a loop to extract the first letter of each sentence, adds that to the element textContent, and then passes the remaining letters back to the function using a setTimeout. If there are no letters left in the sentence, another setTimeout is called after two seconds, resetting the textContent, and then calling the loop again with the next sentence in the array.

const texts = ["get a quote", "get a Tweet"];
const div = document.querySelector('div');

function type(texts) {

  // The index initially points to the
  // first array element
  let index = 0;

  function loop(str) {

    // If the string still has letters
    if (str.length) {

      // Destructure the first letter from it
      // add assign all the other letters to `rest`
      const [ letter, ...rest ] = str;

      // Add the letter to the textContent
      div.textContent += letter;
      
      // Then call the function again with the
      // rest of the letters
      setTimeout(loop, 100, rest);

    // If there are no letters left increase the index,
    // check to see if the array has that index,
    // then, after two seconds, reset the textContent
    // and call the function again with a fresh sentence
    } else {
      ++index;
      if (index < texts.length) {
        setTimeout(() => {
          div.textContent = '';
          loop(texts[index]);
        }, 2000);
      }
    }
  }

  loop(texts[0]);

}

type(texts);
<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