Atin Atin - 6 days ago 5
Javascript Question

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?

Answer

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