简体   繁体   中英

Nested for-loop with delay on each iteration in JavaScript

I am trying to implement a nested for-loop with a delay in each iteration.

So far I've came up with something like this

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

})();

Yet it doesn't work properly. I am trying to make a visual representation of a bubble sort and I need this delay so as to see each step which is kind of impossible if array sorts immediately without this delay. Is it actually possible to implement such thing? Or maybe there is a better way to do this?

The structure you've got seems a bit complex, this should accomplish what you're looking for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM