Welcome , I tring to animate diffrent kinds of sorting alogrithms for now i want to setup animation with first that is bubble sort.My problem is when i click the start button to run the animation the whole browser crushes I am aware that this is triggered by the sorting function but I have no idea what to do so that there is no such problem.
this is my code for drawingVisualisation
import * as d3 from "d3";
const drawVisualization = (data: number[]) => {
const margin = { top: 10, right: 30, bottom: 30, left: 40 };
const width = 800 - margin.left - margin.right;
const height = 400 - margin.top - margin.bottom;
// If it is .visualization del it first
d3.select(".visualization").selectAll("rect").remove();
d3.select(".visualization").select("svg").remove();
const svg = d3
.select(".visualization")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
const rects = svg.selectAll("rect").data(data).enter().append("rect");
rects
.attr("x", (_d, i) => i * (width / data.length))
.attr("y", (d) => height - d)
.attr("width", () => width / data.length - 1)
.attr("height", (d) => d)
.on("mouseover", function (_d, i) {
d3.select(this.parentElement)
.append("text")
.text(i)
.attr(
"x",
() =>
data.indexOf(i) * (width / data.length) + width / data.length / 2
)
.attr("y", height - i - 20)
.attr("font-size", "14px")
.attr("fill", "blue")
.attr("text-anchor", "middle");
d3.select(this).style("opacity", 0.85);
})
.on("mouseleave", function () {
d3.select(this.parentElement).select("text").remove();
d3.select(this).style("opacity", 1);
});
const startButton = document.querySelector(
".run-sorting-btn"
) as HTMLButtonElement;
startButton.addEventListener("click", () => {
for (let i = 0; i < data.length - 1; i++) {
for (let j = 0; j < data.length - i - 1; j++) {
if (data[j] > data[j + 1]) {
const temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
// Animate the movement here
rects
.data(data)
.transition()
.delay((d, i) => i * 50)
.duration(500)
.attr("x", (_d, i) => i * (width / data.length));
}
}
}
});
};
export default drawVisualization;
And from this function this is the trouble maker:
const startButton = document.querySelector(
".run-sorting-btn"
) as HTMLButtonElement;
startButton.addEventListener("click", () => {
for (let i = 0; i < data.length - 1; i++) {
for (let j = 0; j < data.length - i - 1; j++) {
if (data[j] > data[j + 1]) {
const temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
// Animate the movement here
rects
.data(data)
.transition()
.delay((d, i) => i * 50)
.duration(500)
.attr("x", (_d, i) => i * (width / data.length));
}
}
}
});
5