微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在执行下一行代码之前等待超时完成

我正在制作一个排序算法可视化工具。我有我的程序的一部分,如果您单击合并排序按钮,它会以红色突出显示正在比较的两个元素,等待 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,midindex + 1,highIndex);

  // Merge the left sides and right sides
  merge(unsortedArray,midindex,highIndex);
}

// Does the actual work of ordering list
async function merge(unsortedArray,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/

解决方法

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

确实如此。您还需要将 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,midIndex + 1,highIndex);
//^^^^^

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。