setTimeout does not work well inside loop

2

I'm making a game in javascript, it's kind of the game genius . using setTimeout inside the for.

function executarJogo(numeroJogada){
    var cores = ["#FFFF00","#00FF00","#0000FF","#FF0000"];
    for (var i = 0; i < numeroJogada; i++) {
        var numQuadro = Math.floor((Math.random() * 4) + 1);
        var corQuadro = Math.floor((Math.random() * 4) + 1);
        var q = "c" + numQuadro;
        console.log(corQuadro -1,cores[corQuadro-1]);
        var quadrado = document.getElementById(q);
        quadrado.style.background=cores[corQuadro-1];
        doTimeOut(quadrado);

    }
}

function doTimeOut (quadrado) {
    setTimeout(function() {quadrado.style.background="#cdc8b1";}, 1000);
}

The problem is: when I run it for 3 times, for example instead of changing the color of a div and returning to normal color, then changing the color of another div and returning to normal, is changing the color of all divs at the same time, as if settimeout were not waiting for 1000 milliseconds.

    
asked by anonymous 13.10.2014 / 15:27

1 answer

4

You have to multiply the number of setTimeout with each call:

var chamadas = 0;
function doTimeOut (quadrado) {
    chamadas++;
    setTimeout(function() {quadrado.style.background="#cdc8b1";}, chamadas*1000);
}

And you should also clear the variable at the end of each round.

var chamadas = 0;

This happens because the loop executes quite fast: that is, assuming:

Execution:

0 -> setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},1000);
1 -> setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},1000);
2 -> setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},1000);

Output:

0 -> 1413210680551
1 -> 1413210680551
2 -> 1413210680552 
  

Notice that the difference is now 1 or no millisecond.

Simulation 2:

var chamadas = 1;
setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},chamadas*1000);
chamadas++;
setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},chamadas*1000);
chamadas++;
setTimeout(function(){var d = new Date(); var t = d.getTime(); console.log(t)},chamadas*1000);

Output:

0 -> 1413210718070
1 -> 1413210719069
2 -> 1413210720069
  

Note that the output now has a 1000 millisecond difference, that is, 1 second.

  

As if settimeout were not waiting for 1000 milliseconds.

It's actually waiting for the 1000 milliseconds, but it's waiting for this time for all outputs.

    
13.10.2014 / 16:26