setTimeout does not work well inside loop

Asked

Viewed 345 times

2

I’m making a game in javascript, it’s like the game Genius.I’m 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 the 3 times for example instead of changing the color of a div and going back to the normal color, then changing the color of another div and going back to normal, is changing the color of all the Ivs at the same time, as if the settimeout wasn’t waiting for the 1000 milliseconds.

1 answer

4


You have to multiply the number of setTimeout every 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 runs very fast: i.e., 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);

Exit:

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

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

Exit:

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

Note that the output now has 1000 milliseconds difference, ie 1 second.


as if the settimeout wasn’t waiting for the 1000 milliseconds.

He’s actually waiting for the 1,000 milliseconds, only he’s waiting that long for all the exits.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.