【问题标题】:I am not able to see the intermediate results for sorting我看不到排序的中间结果
【发布时间】:2021-11-08 02:55:28
【问题描述】:

我正在使用 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 被着色并改变高度。 排序完成后,我只能看到整个排序 那么这里的问题是什么? 如何解决?

【问题讨论】:

  • 忙着等待(几乎)不是一个好主意。
  • 但它是为了展示事情是如何完成的。有没有其他办法?

标签: javascript html css dom css-transitions


【解决方案1】:

当您的代码在运行时,UI 不会更新(不会有任何渲染,否则如果网页会通过 JavaScript 更新动态内容,网页会闪烁!),因此您的忙碌等待只会浪费CPU 周期。

使整个事情异步并使用超时等待:const sleep = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms)) 将为您提供一个休眠给定时间的异步函数,然后您可以将您的代码设置为 async function(因此您可以使用 @987654323 @) 并使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多