2016-12-01 73 views
1

我試圖在每次迭代中實現一個嵌套的for循環。在JavaScript中的每次迭代中嵌套的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(); 

})(); 

然而,它不能正常工作。我試圖做一個氣泡排序的可視化表示,並且我需要這個延遲以便看到如果數組立即排序而沒有這個延遲,那麼每個步驟都是不可能的。實際上有可能實現這樣的事情嗎?或者也許有更好的方法來做到這一點?

+1

定義「工作不正常」? –

+0

您正在調用'nNext',然後以遞歸方式再次調用它。那真的是你想要的嗎? – 2016-12-01 19:17:06

+0

另外,在外層'setTimeout'中,傳遞一個箭頭函數,該函數具有一個可立即調用名爲'next'的函數的主體。爲什麼?看起來像箭頭函數可以被刪除,以及立即調用'next',並且只傳遞'function next(){...}'。 – 2016-12-01 19:19:41

回答

0

你已經有了結構似乎有點複雜,這應該做到你在找什麼:

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()