我正在使用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被着色和改变高度。我只能在排序完成后才能看到整个排序,那么这里有什么问题呢?如何解决这个问题?
发布于 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。
下面是一个异步等待的工作示例:
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>
https://stackoverflow.com/questions/69152102
复制相似问题