JavaScript设置执行的超时顺序
我正在构建一个排序算法可视化工具,一个简化版本。如果没有setTimeout函数,数组会按预期对自身进行排序,并且条的顺序正确。但是我想让它像在那个例子中那样动画化,但是在添加setTimeout函数之后,我得到了我想要的效果,但是它发生了混乱,排序错误。我知道超时函数是在主线程之后执行的,但我不明白为什么这是一个问题,例如,当间隔为0时,它不应该仍然正确地对数组排序吗?据我所知,setTimeout函数将以相同的顺序运行 我试着在两个设置超时中使用不同的间隔,但即使在0时,也会出现无序情况,数组排序不正确。对于上下文,updateSlowPointer和updateFastPointer要做的就是突出显示我们正在查看的第j条和第j+1条。交换,交换两个条,只需交换CSS类JavaScript设置执行的超时顺序,javascript,asynchronous,Javascript,Asynchronous,我正在构建一个排序算法可视化工具,一个简化版本。如果没有setTimeout函数,数组会按预期对自身进行排序,并且条的顺序正确。但是我想让它像在那个例子中那样动画化,但是在添加setTimeout函数之后,我得到了我想要的效果,但是它发生了混乱,排序错误。我知道超时函数是在主线程之后执行的,但我不明白为什么这是一个问题,例如,当间隔为0时,它不应该仍然正确地对数组排序吗?据我所知,setTimeout函数将以相同的顺序运行 我试着在两个设置超时中使用不同的间隔,但即使在0时,也会出现无序情况,数
let bubbleSort = (inputArr) => {
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
setTimeout(() => {
updateSlowPointer(inputArr[j], inputArr[j - 1]);
updateFastPointer(inputArr[j + 1]);
}, 0);
if (inputArr[j] > inputArr[j + 1]) {
setTimeout(() => {
swap(inputArr[j], inputArr[j + 1]);
}, 0);
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
}
}
}
return inputArr;
};
让bubbleSort=(inputArr)=>{
设len=inputArr.length;
for(设i=0;i{
updateSlowPointer(inputArr[j],inputArr[j-1]);
updateFastPointer(inputArr[j+1]);
}, 0);
if(inputArr[j]>inputArr[j+1]){
设置超时(()=>{
交换(inputArr[j],inputArr[j+1]);
}, 0);
设tmp=inputArr[j];
inputArr[j]=inputArr[j+1];
inputArr[j+1]=tmp;
}
}
}
返回输入端;
};
正确获取循环和异步是复杂的。但是我们有一个工具来实现它:async
函数!然后,您可以轻松地等待循环。或者,如果您希望能够一步一步地运行算法,我认为您需要,生成器函数可能是您选择的工具:
function* bubbleSort(inputArr) {
let len = inputArr.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
updateSlowPointer(inputArr[j], inputArr[j - 1]);
updateFastPointer(inputArr[j + 1]);
}
if (inputArr[j] > inputArr[j + 1]) {
swap(inputArr[j], inputArr[j + 1]);
}
let tmp = inputArr[j];
inputArr[j] = inputArr[j + 1];
inputArr[j + 1] = tmp;
yield inputArr; // < let other code step in here
}
return inputArr;
}
但是您的
if
s检查当前状态,而您的突变是异步发生的
const timer = ms => new Promise(res => setTimeout(res, ms));
(async function() {
let stepper = bubbleSort([1, 3, 2]), done = false;
while(!done) {
({ done, value }) = stepper.next();
// visualization here
console.log(value);
await timer(1000);
}
})();