0👍
Solved this issue by switching approach by utilising a sleep promise that has a setTimeout and making the sorting algorithm function asynchronous.
It now steps through the animations of the algorithm at a speed that properly visualises the sorting process.
Code Below:
async bubbleSort(){
console.log("Running Bubble Sort")
var is_sorted = false;
var counter = 0;
while(!is_sorted){
is_sorted = true;
for( let i = 0; i < (this.num_list.length - 1 - counter); i++){
// set compared values for coloring
this.compare_val_1 = this.num_list[i];
this.compare_val_2 = this.num_list[i +1];
// check if values need to be swapped
if(this.num_list[i] > this.num_list[i + 1]){
this.swapNumbersInArray(i, i+1)
await this.sleep(5) // short delay so user can see the animation
is_sorted = false;
}
}
counter =+ 1
}
this.sorted = true; // changes color to finalColor
},
sleep(ms){
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
},
Source:stackexchange.com