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!