我看不到排序的中间结果

I am not able to see the intermediate results for sorting

我正在使用 JS、HTML 和 CSS 制作排序算法可视化工具,为了显示冒泡排序,我编写了以下代码

for (let i = 0; i < elements; i++) {
  for (let j = 0; j < elements; j++) {

    let a = temp[i].style.height;
    let b = temp[j].style.height;

    //this is to show the current elements begin compared
    temp[i].style.backgroundColor = 'green';
    temp[j].style.backgroundColor = 'blue';

    if (parseFloat(a) < parseFloat(b)) {

      //if the elements need to be swapped then the following code will change its height
      let t = a;
      temp[i].style.height = b;
      temp[j].style.height = t;


    }

    //this is to slow down the process                    
    sleep(500);

    //this is to change back the div's background to normal
    temp[i].style.backgroundColor = 'white';
    temp[j].style.backgroundColor = 'white';

  }
}
}

function sleep(num) {
  var now = new Date();
  var stop = now.getTime() + num;
  while (true) {
    now = new Date();
    if (now.getTime() > stop) return;
  }
}

但这里的问题是我无法看到任何中间结果,例如看到两个 div 被着色和改变高度。 我只能在排序完成后才能看到整个排序 那么这里的问题是什么? 如何解决这个问题?

虽然您的代码是 运行,但 UI 没有更新(不会有任何渲染,否则如果网页有由 [=32= 更新的动态内容,网页会闪烁) ]!),因此您的忙碌等待只会浪费 CPU 个周期。

使整个事情异步并使用超时等待:const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) 会给你一个异步函数,它会在给定的时间内休眠,然后你可以让你的代码成为 async function (所以你可以使用 await) 并使用 await sleep(500) 而不是 sleep(500).

由于代码现在不再同步,它不会阻塞事件循环,并允许 UI 在您等待时更新。

下面是一个异步等待的工作示例:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

const counter = document.getElementById('counter')
const countButton = document.getElementById('count-button')

async function count () {
  countButton.disabled = true
  
  counter.innerText = 'One...'
  await sleep(1000)
  counter.innerText = 'Two...'
  await sleep(1000)
  counter.innerText = 'Three...'
  await sleep(1000)
  counter.innerText = 'Done!'
  
  countButton.disabled = false
}

countButton.addEventListener('click', () => {
  // It's important to catch any asynchronous error here so it can be handled
  // regardless of where it happens in the process - otherwise it will become
  // an unhandled promise rejection.
  count().catch(e => console.error('An error occured during counting!', e))
})
<h1 id="counter">...</h1>
<button id="count-button">Count!</button>