I am new to javascript so sorry if I am misunderstanding how the language does some stuff, I am building a sorting algorithms visualizer which orders blocks by their hue value (using chroma-js library) : Each item in screenObject.items is a Color object
//color objects are what I am sorting
class Color {
constructor(div, color, value) {
//this div on the html page
this.div = div;
this.color = color;
//hue value of the color
this.value = value;
}
update(color, value) {
this.color = color;
this.value = value;
this.div.style.backgroundColor = color;
}
}
class ScreenObject {
constructor() {
//this is an array of color objects
this.items = [];
}
bubbleSort() {
let solved = false;
while (!solved) {
let swaps = 0;
this.items.forEach((item, index) => {
if (index > 0) {
swaps += compare(this.items[index - 1], item);
}
});
if (swaps === 0) {
solved = true;
}
}
}
}
function compare(color1, color2) {
if (color1.value > color2.value) {
swap(color1, color2);
return 1;
} else {
return 0;
}
}
function swap(color1, color2) {
colorStore = color1.color;
valueStore = color1.value;
color1.update(color2.color, color2.value);
color2.update(colorStore, valueStore);
}
The issue I have is that this colors only update after the program is completed, and if I add an setIterval, or setTimeout I have only been able to make the colors update after each pass, instead of after each comparison/swap (I want to add special styling when the colors are being compared):
bubbleSort() {
let solved = false;
while (!solved) {
let swaps = 0;
setInterval(() => {
this.items.forEach((item, index) => {
if (index > 0) {
swaps += compare(this.items[index - 1], item);
}
});
}, 50);
if (swaps === 0) {
solved = true;
}
}
}
I want to be able to see the colours update after every single comparison for example swap(1, 2) the user sees 1 get 2's color and 2 get 1's color.
Thanks in advance!