Monday, February 20, 2012

Parameters for setTimeout payload (JavaScript)

A step in building an implementation of Conway's Game of Life with my son - make the game turns going on the web page. What is not obvious for him yet is why it is important to avoid global objects to feed as parameters to setTimeout function or just keep around. But it can be done - easily:

var game = function(times, interval){
    game.times = times;
    game.interval = interval;
    game.turn = function(){
        if (times > 0) {
            console.log("You have " + times + " turns left");
            times = times - 1;
            setTimeout(game.turn, interval, game);
        } else {
            console.log("Game over!");
        };
    };
    game.turn();
};

game( 10, 1000 );