Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

83
Vistas
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!

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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>

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos