我正在尝试实现嵌套的for循环,每次迭代都有延迟。
到目前为止,我已经想到了这样的事情
var maxLoops = 10 ;
var counter = 0;
var counter2 = counter;
var maxLoops = 10 ;
var counter = 0;
var counter2 = counter;
(function nNext() {
if (counter == maxLoops) return
counter2 = counter - 1;
setTimeout(() => (function next() {
if (counter2 >= maxLoops) return;
setTimeout(() => {
console.log( "Nester counter :" + counter2);
counter2++
next()
}, 100)
})(), 1)
counter++;
nNext();
})();
但是它不能正常工作。我试图对气泡排序进行可视化表示,但我需要此延迟,以便看到每个步骤,如果数组没有此延迟立即排序,则这是不可能的。实际上有可能实现这种事情吗?也许有更好的方法可以做到这一点?
最佳答案
您所拥有的结构似乎有点复杂,这应该可以满足您的需求:
var maxLoops = 10,
counter = 0,
counter2 = 0;
function outerNext() {
if (counter == maxLoops) return;
counter2 = counter - 1
innerNext()
}
function innerNext() {
if (counter2 >= maxLoops) {
outerNext()
}
else {
counter2++;
console.log("Nester counter :" + counter2);
setTimeout(innerNext, 500)
}
}
outerNext()