【发布时间】:2022-12-31 02:11:34
【问题描述】:
我正在编写一个程序,在反应中可视化合并排序。我想允许用户使用滑块来更改排序速度。我在 for 循环中使用 setTimeout 函数来安排迭代等间隔的时间间隔。我想以某种方式使从滑块获得的值反映在 setTimeout 中,但是,由于循环会立即执行并安排循环的迭代,因此在执行程序时会立即计算延迟值。
const MergeSort = () => {
let animations = sortingAlgorithms.mergeSort(array);
console.log(animations.length);
for (let i = 0; i < animations.length; i++) {
// speed++;
// console.log(i);
setTimeout(() => {
// setSpeed(tempSpeed);
const topArrayBars = document.getElementsByClassName("array__bar");
const bottomArrayBars =
document.getElementsByClassName("array__baraux");
if (animations[i].type === "look") {
for (let j = 0; j < topArrayBars.length; j++) {
topArrayBars[j].style.backgroundColor = "rgb(57, 200, 195)";
}
for (let j = animations[i].look[0]; j <= animations[i].look[1]; j++) {
topArrayBars[j].style.backgroundColor = "rgb(255, 79, 120)";
}
} else if (animations[i].type === "join") {
for (let j = 0; j < topArrayBars.length; j++) {
topArrayBars[j].style.backgroundColor = "rgb(57, 200, 195)";
}
// left color
for (
let j = animations[i].leftIndices[0];
j <= animations[i].leftIndices[1];
j++
) {
topArrayBars[j].style.backgroundColor = "rgb(255, 77, 252)";
}
// right color
for (
let j = animations[i].rightIndices[0];
j <= animations[i].rightIndices[1];
j++
) {
topArrayBars[j].style.backgroundColor = "rgb(255, 237, 77)";
}
} else if (animations[i].type === "place") {
bottomArrayBars[animations[i].newIdx].style.height =
topArrayBars[animations[i].oldIdx].style.height;
bottomArrayBars[animations[i].newIdx].style.backgroundColor =
topArrayBars[animations[i].oldIdx].style.backgroundColor;
topArrayBars[animations[i].oldIdx].style.backgroundColor =
"rgba(57, 200, 195, 0)";
} else if (animations[i].type === "lift") {
for (
let j = animations[i].range[0];
j <= animations[i].range[1];
j++
) {
topArrayBars[j].style.height =
animations[i].newVals[j - animations[i].range[0]].toString() +
"px";
topArrayBars[j].style.backgroundColor = "rgb(57, 200, 195)";
}
for (let j = 0; j < topArrayBars.length; j++) {
topArrayBars[j].style.backgroundColor = "rgb(57, 200, 195)";
}
for (let j = 0; j < bottomArrayBars.length; j++) {
bottomArrayBars[j].style.backgroundColor = "rgba(57, 200, 195, 0)";
}
}
}, i * getSpeed());
}
上面的 getSpeed 函数尝试从滑块控制的名为 speed 的 useState 变量中提取速度。但是,我无法弄清楚如何让程序等着看滑块值是多少来改变动画的速度。
我想以某种方式让循环迭代如下: 执行一次 检查速度值,并等待 1/speed 再次执行 检查速度值并等待 1/speed ...
【问题讨论】:
-
只是不要一次安排所有动画。安排一个,然后一旦你完成了,查看速度滑块的当前值并安排下一个,直到你没有动画。
标签: javascript reactjs animation settimeout delayed-execution