【发布时间】: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