I'm trying to mimic a simple sorting algorithm and use React setState to store the sorted array (as "output") in real-time with an interval of 100ms so it can show on the screen as an algorithm visualizer. The sorted array can be displayed in the console but the React state is not updating real-time accordingly. How can I fix this?
const [output, setOutput] = useState([]);
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
const Simple_Sorting_Algo = (n) => {
const array = [];
for (var i = 0; i < n; i++) {
array.push(Math.floor(Math.random() * 1000)); //generating a random array
}
const sortedArr = [...array];
const send = async () => {
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (sortedArr[i] > sortedArr[j]) {
var tmp = sortedArr[i];
sortedArr[i] = sortedArr[j];
sortedArr[j] = tmp;
console.log(sortedArr);
setOutput(sortedArr);
console.log(output);
await timer(100); //delay
}
}
}
};
send();
};