Joseph Clark
Joseph Clark

Reputation: 37

variable value changing does not delay setTimeout?

I am making a red light green light type game. Here is the part where the stoplight changes color:

var green = function() {
    var r = Math.floor(Math.random() *5000 + 3000);
    ctx.fillStyle = "green";
    ctx.fillRect(900, 580, 200, 100);
    green = true;
    setTimeout(red, r);
};
var red = function() {
    var r = Math.floor(Math.random() *3000 + 2000);
    ctx.fillStyle = "red";
    ctx.fillRect(900, 580, 200, 100);
    green = false;
    setTimeout(green, r);
};

If I take out the variable green, then it works fine but I need it so the game knows when the player can and cant move. I would appreciate any help!

Upvotes: 0

Views: 46

Answers (1)

Ronen Cypis
Ronen Cypis

Reputation: 21470

You override the variable green.

Initially it is a function, and inside the red function, you assign true to it. That's the reason your setTimeout(green,r); doesn't work.

Upvotes: 1

Related Questions