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

405
Visualizações
setInterval vs setTimeout which is better to run a loop at a specified speed
var speed = 200,
  len = 0;
if (e in know) {
  function typing() {
    if (len < know[e].length) {
      if (len === know[e].length - 1) {
        t.innerHTML = know[e];
        g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
        if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
        else alert("new message");
      }
      len++;
      setTimeout(typing, speed);
    }
  }
  typing();

setTimeout vs setInterval code...

var setIn = setInterval(() => {
  if (len < know[e].length) {
    if (len === know[e].length - 1) {
      clearInterval(setIn);
      t.innerHTML = know[e];
      g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
      if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
      else alert("new message");
    }
    len++;
  }
}, speed)

I'm trying to make a reply bot that starts typing after 1 seconds and that will reply back at the speed of the String.length and they both did the same thing but someone once told me using setTimeout is bad practice, but I need them to run that exact way. If there is another work around for it I'm open to all suggestions, Thanks in advance.

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

0

You can have multiple approaches:

  1. setInterval
  2. setTimeout
  3. window.requestAnimationFrame

If you need to wait for 1 second, then you must have a setTimeout and inside, I encourage you to use the 3rd option if you want to save performance, but combining setTimeout with setInterval is an available option. The use of them is not a bad practice in general, just in particular cases.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use async/await to emulate typing and create delays:

//
// Async timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

//
// Bot typing function
const runBot = text => {
  // Use promises
  return new Promise(async (resolve, reject) => {
    // DOM
    const div = document.getElementById('text');
    
    // Create chars array
    const chars = text.split('');
    
    // Wait 1 sec before typing
    await timeout(1000);
    
    // Type text
    while(chars.length) {
      // Put one char at iteration
      div.innerHTML += chars.shift();
      
      // Wait some amount
      await timeout(100);
    }
    
    // Add new line to the text box
    div.innerHTML += '<br>'
    
    // Finish function
    return resolve();
  });
}

//
// Text typing runner and button controller
const typeText = async text => {
  // DOM
  const button = document.querySelector('button');
  
  // Disable button
  button.disabled = true;
  
  // Run bot and wait till it finishes
  await runBot(text);
  
  // Enable button
  button.disabled = false;
}
<div id="text" style="padding:10px;border:1px solid #000"></div>
<button onClick="typeText('This is demo text!')">Start bot</button>

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