Diana Ayala Diana Ayala - 1 month ago 12
Javascript Question

can´t manage timeouts in for loop in javascript

I'm trying to do some kind of Simon game in javascript. I have already made a table, and a function that changes any cell by its id to another id, so it's color changes for 300 miliseconds. This is the code:

var seleccionarcelda = function(object){
var id=object.id;
object.id="selected";
setTimeout(function(){object.id=id;},300);
}


Then, for a sequence as large as I want it to, it should light a random cell, and then another cell, in a for loop

var secuencia = function(numero){
for(j=0; j<numero; j++){
var cel="t"+ Math.floor((Math.random() * 6) + 1);
console.log(cel);
seleccionarcelda(document.getElementById(cel));
}
}


The problem is that it kind of works, but selects all cells at once, and not in order as it should do. How can I fix it?

Answer Source

You could pass the loop index into the function and use that as a multiplier of the delay time.

Something like:

var seleccionarcelda = function(object, index){
  // increment delay timer
  var delay = (index + 1) * 300;

  var id=object.id;
  object.id="selected";
  setTimeout(function(){object.id=id;}, delay );// use variable for timer delay
}

var secuencia = function(numero){
  for(j=0; j<numero; j++){
      var cel="t"+ Math.floor((Math.random() * 6) + 1);
      console.log(cel);
      // pass j to function
      seleccionarcelda(document.getElementById(cel), j);
  }
}

What is happening now is the loop completes in milliseconds and therefore all the setTimeout start at basically the same time