I'm working on visual version of my sorting algorithm and I would like to show to the user a loading animaton during the sorting itself by JS. But the problem is that JS behaves weird then. It executes the first line and the last line (2 x toggle) and the launches the execution of the alogrithm. But if I add setTimeout (2nd function) it works as it should. Could anyone, please, explain to me how it works ? I've already tried to do a lot of reasearch but to no avail... It's counter-intuitive - because in first example it behaves like JS was asynchronous (1 -> first line animation added and 2 -> the last line animation removed, 3 -> the sorting work) and in the second example after adding setTimeout as synchronous (1 -> first line animation added, 2 -> sorting work, 3 -> animation removed)
function sortArray() {
mainWrapper.classList.toggle("spinner-hidden");
arrayCopy = [...arrayToSort];
const sortedArray = bearSort(arrayCopy);
outputArray.textContent = sortedArray;
mainWrapper.classList.toggle("spinner-hidden");
}
function sortArray() {
mainWrapper.classList.toggle("spinner-hidden");
arrayCopy = [...arrayToSort];
setTimeout(() => {
const sortedArray = bearSort(arrayCopy);
outputArray.textContent = sortedArray;
mainWrapper.classList.toggle("spinner-hidden");
}, 0);
}