首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我看不到排序的中间结果

问我看不到排序的中间结果
EN

Stack Overflow用户
提问于 2021-09-12 13:59:09
回答 1查看 36关注 0票数 0

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

代码语言:javascript
复制
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被着色和改变高度。我只能在排序完成后才能看到整个排序,那么这里有什么问题呢?如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-12 14:11:10

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

使整个过程异步并使用超时等待:const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))将为您提供一个异步函数,该函数在给定的时间内休眠,然后您可以使您的代码成为一个async function (因此您可以使用await),并使用await sleep(500)而不是sleep(500)。

因为代码现在不再是同步的,所以它不会阻塞事件循环,并允许在您等待的同时更新UI。

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

​

代码语言:javascript
复制
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))
})
代码语言:javascript
复制
<h1 id="counter">...</h1>
<button id="count-button">Count!</button>

​

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69152102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档