Search code examples
javascriptloopsdelay

add a delay in a double loop


In this code (source: eloquent javascript) i want to add a delay of 1 second for any of these 2 loops but i do not manage in any way. I would like to see how that can be solved with setTimeout for each of loops and for both (each iteration to be executed 1 second one after the other, thank you. I failed to get this working from similar questions/answers.

let board = "";

for (let y = 0; y < 8; y++) {
  for (let x = 0; x < 8; x++) {
    if ((x + y) % 2 == 0) 
         {board += " ";}
    else {board += "#";}
  }
  board += "\n";
}

console.log(board);


Solution

  • You could use generators in combination with setinterval to call iterator#next every second. So in the following example, just do yield board whenever you want to wait 1 second.

    function* looping() {
      let board = "";
      for (let y = 0; y < 8; y++) {
        for (let x = 0; x < 8; x++) {
          board += (x + y) % 2 ? "#" : " ";
          yield board;
        }
        board += "\n";
      }
      return board;
    }
    
    var iterator = looping();
    
    (function iife() {
      setTimeout(function() {
        var result = iterator.next();
        document.querySelector("#result").textContent = result.value;
        if (!result.done) iife();
        else console.log("Done");
      }, 1000);
    })();
    #result {
      white-space: pre;
    }
    
    #result::before,
    #result::after {
      content: '"';
    }
    <div id="result"></div>