0

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!

Jack Z
  • 53
  • 5

1 Answers1

1

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>
yonizilberman
  • 424
  • 4
  • 9
  • Thank you!!! I combined that with https://stackoverflow.com/questions/41282721/how-can-i-animate-dom-elements-in-a-loop-with-interval-between-each-iteration?rq=1 and it worked!!!! – Jack Z Jun 29 '22 at 08:13