JavaScript代码正在同时运行,并且没有等待



我正在用javascript制作一个排序可视化工具。这是排序算法之一的示例:选择排序但是当我运行代码时,即使选择排序visualizer.compare和visualizer.swap函数有1秒的暂停-数组立即排序,而不是暂停。我认为这是因为javascript运行异步,因为如果我将代码转换为一个超时,它会像正常情况一样运行,除非在超时时间过去后,所有高度都会同时更改,这很奇怪

所有代码都是通过向单击时运行selectionSort函数的按钮添加单击事件来运行的(github代码https://github.com/Jalrux/sorting-visualizer)

function selectionSort(array, visualizer) {
let arrayLength = array.length;
let minIndex;
// loop through the array and sort each value array
for (let i = 0; i < arrayLength; i++) { // loop through all indexes of array   
minIndex = i; // assume that element with i index is minimum
// Find the minimum element in unsorted array 
for (let j = i + 1; j < arrayLength; j++) { // loop through indexes of unsorted elements

visualizer.compare(i, j); // run the comparing visualizer
if (array[minIndex] > array[j]) { // check if the element of minIndex is larger than value of the index j
minIndex = j; // set minIndex to j
}
}
visualizer.swap(minIndex, i); // run the swapping visualizer
let temp = array[i]; // Swap the minimum element with element of index i 
array[i] = array[minIndex];
array[minIndex] = temp;

visualizer.finished(i); // change the color of the bars at index minIndex to the finished color
}
}
export {selectionSort, generateArray};

这是visualizer.js文件中交换函数的代码

// change the colors of 2 bars to the swapping color and swap
export function swap(index1, index2) {
let bar1Style = arrayBars()[index1].style;
let bar2Style = arrayBars()[index2].style;
// save the previous colors
let bar1Color = bar1Style.backgroundColor;
let bar2Color = bar2Style.backgroundColor;  

// change the colors to the comparing color
bar1Style.backgroundColor = swapColor;
bar2Style.backgroundColor = swapColor;

// swap the heights of the bars
pause();
let bar1height = bar1Style.height;
let bar2height = bar2Style.height;
bar1Style.height = bar2height;
bar2Style.height = bar1height;
pause(); 
// change the colors back to their original colors
bar1Style.backgroundColor = bar1Color;
bar2Style.backgroundColor = bar2Color;
}

// some helper functions that are in the visualizer.js file
export function arrayBars() {
return document.getElementsByClassName('array-bar');
}
// sleeps for pauseTime seconds 
export function pause() {
setTimeout(function() {}, pauseTime);    
}

可能对async/await使用基于承诺的延迟。

function delay(time) {
return new Promise(res => {
setTimeout(() => res(), time);
});
}
async function main() {
console.log('First... waiting for two seconds');
await delay(2000);
console.log('Second... waiting for five seconds');
await delay(5000);
console.log('Done');
}
main();

最新更新