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

时间:2021-05-07 21:14:23

标签: javascript asynchronous async-await promise timeout

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

为了让程序等待 1000 毫秒,我使用以下方法。它在我的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/

1 个答案:

答案 0 :(得分:1)

<块引用>

我有一个理论,这是因为我使用的暂停方法只暂停异步函数,但不能完全确定这是否正确。

确实如此。您还需要将 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);
//^^^^^
}