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

197
Visualizações
Slowing Down Each Iteration of Loop Dom Manipulation

I have having some trouble with slowing down the loop of a for and while loop in javascript.

const insertion_sort = function (array) {
  for (i = 1; i < array.length; i++) {
    let key_item = array[i];
    let j = i - 1;

    while (j >= 0 && array[j] > key_item) {
      array[j + 1] = array[j];
      j--;
      //change HTML through dom manipulation;
    }

    array[j + 1] = key_item;
  }
  return array;
};

The code is above. I do have a function that changes the dom that actually does work when I put it into my function. It only shows the end result which is align with what I want. However, the problem is the loops executes very fast and it's not able to show the dom manipulation at each iteration of the loop. What I think I should do is I should slow down the loop, but the set time out function does not seem to work. As far as I can tell, promises don't work either since it's asynchronous so I am not exactly sure how I would slow down the loop so that a user is able to see each iteration of the dom manipulation. Any help would be greatly appreciated. Or perhaps my understanding of timeout function and promises is not correct. Thanks!

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

0

Did you tried something like this:

const val = document.getElementById('test')
const array = [500, 1000, 2000, 3000, 4000]

function someAPICall(time) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Resolved")
    }, time);
  })
}


array.forEach(async(i) => {
  const res = await someAPICall(i);
  val.innerHTML = i
})
<div id="test">0</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