在执行下一行代码之前等待超时完成

Waiting for timeout to finish before executing next line of code

我正在制作一个排序算法可视化工具。我的程序有一部分,如果您单击合并排序按钮,它会以红色突出显示正在比较的两个元素,等待 1000 毫秒,然后在比较完成后将元素变回海蓝宝石。

为了让程序等待1000ms,我使用了下面的方法。它在我的 bubbleSort 实现中工作得很好,但由于某种原因在 mergeSort 中不起作用:

await new Promise(r => setTimeout(r, 0.1));

我有一个理论,这是因为我使用的暂停方法只是暂停异步函数,但不完全确定这是否正确。实际上发生的情况是,一旦程序到达 await new Promise() 行,它就会返回到 while 语句并从那里执行,而不是等待 1000 毫秒,然后执行本来会变成的行barA 和 barB 变回海蓝宝石。

function mergeSort(unsortedArray, aux = [...unsortedArray], lowIndex = 0, highIndex = unsortedArray.length - 1) {
  console.log(unsortedArray);

  // Base case
  if (highIndex === lowIndex) return;

  // Get midIndex
  const midIndex = Math.floor((highIndex + lowIndex) / 2);

  // Recursively run left side and right side until base case reached.
  mergeSort(unsortedArray, aux, lowIndex, midIndex);
  mergeSort(unsortedArray, aux, midIndex + 1, highIndex);

  // Merge the left sides and right sides
  merge(unsortedArray, aux, lowIndex, midIndex, highIndex);
}

// Does the actual work of ordering list
async function merge(unsortedArray, aux, lowIndex, midIndex, highIndex) {
  let auxkey = lowIndex;
  let i = lowIndex;
  let j = midIndex + 1;

  // While there are elements in left/right sides, put element in auxillary array
  // then increment the indexes by 1.
  while (i <= midIndex && j <= highIndex) {
    let arrayBars = document.getElementsByClassName('bar');
    const barA = arrayBars[i].style; 
    const barB = arrayBars[j].style;
    barA.backgroundColor = "red";
    barB.backgroundColor = "red";

    if (unsortedArray[i] <= unsortedArray[j]) {
      aux[auxkey] = unsortedArray[i];
      auxkey++;
      i++;
    } else {
      aux[auxkey] = unsortedArray[j];
      auxkey++;
      j++;
    }

    await new Promise(r => setTimeout(r, 0.1));
    barA.backgroundColor = "aquamarine";
    barB.backgroundColor = "aquamarine";
  }
}

这是我的代码的精简版本。稍微全面一点的请看:https://jsfiddle.net/SushiCode/k0954yep/9/

I have a theory that this is because the pausing method I used only pauses the async function but not entirely sure if that is correct.

确实如此。您还需要将 mergeSort 函数标记为 async,这样您就可以 await merge() 以及两个递归 mergeSort() 调用。

async function mergeSort(unsortedArray, aux = [...unsortedArray], lowIndex = 0, highIndex = unsortedArray.length - 1) { /*
^^^^^ */
  if (highIndex === lowIndex) return;

  const midIndex = Math.floor((highIndex + lowIndex) / 2);

  await mergeSort(unsortedArray, aux, lowIndex, midIndex);
//^^^^^
  await mergeSort(unsortedArray, aux, midIndex + 1, highIndex);
//^^^^^

  await merge(unsortedArray, aux, lowIndex, midIndex, highIndex);
//^^^^^
}