I'm new to JavaScript and I'm trying to write a simple game-loop. Here's my Game object:
var Game = {
timers: [],
start: timestamp(),
stopTimers: function() {
consoleEntry('All timers have been stopped.');
this.timers.length = 0;
},
update: function(elasped) {
for (var i = 0; i < this.timers.length; ++i) {
var timer = elapsed - timers[i].startTime;
console.log('Timer: ' + timer + '. Timer interval: ' + this.timers[i].interval + '.');
if (this.timers[i].interval <= timer) {
this.timers[i].times--;
this.timers[i].report = true;
if (this.timers[i].times != 0) {
this.timers[i].startTime = elapsed;
}
}
}
},
render: function() {
for (var i = 0; i < this.timers.length; ++i) {
if (this.timers[i].report) {
consoleEntry('Timer: ' + this.timers[i].name + ' (' + this.timers[i].times + ' remaining).');
this.timers[i].report = false;
if (this.timers[i].times == 0) this.timers.splice(i, 1);
}
}
},
gameLoop: function() {
var elapsed = timestamp() - this.start;
this.update(elapsed);
this.render();
requestAnimationFrame(this.gameLoop);
},
startGame: function() {
console.log(this);
requestAnimationFrame(this.gameLoop);
}
}
I call Game.startGame();
when the <body>
loads. Here's the error I receive: Uncaught TypeError: undefined is not a function
. It refers to this.update(elapsed);
inside the gameLoop
function. For some reason I don't understand, when I do console.log(this)
inside startGame
I get the object it belongs to (which is awesome), but when I do the same inside gameLoop
, I get the Window
object.
Does anyone know why this happens?
Thank you!