I'm trying to call a portion of code in a class over and over again at every second,
update() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
entity.y += 1;
renderAliens(entity, this.context);
}
}
}
this is the code I am trying to call inside of my Game object using
setInterval(newGame.update(),1000), however when I attempt to do this it errors saying that Uncaught TypeError: this.entities is undefined, I understand that this is due to a scope issue with this and setinterval, yet I am unsure how to use bind to solve the issue
edit: here's the whole piece of relevant code
class Game {
constructor() {
this.gameOver = false;
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
}
start() {
this.entities.push(new Ship(0, 400));
this.entities.push(new Alien(1, 0));
this.entities.push(new Alien(20, 0));
this.entities.push(new Alien(40, 0));
}
render() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
renderAliens(entity, this.context);
} else if (entity instanceof Ship) {
renderShip(entity, this.context);
}
}
}
update() {
for (let entity of this.entities) {
if (entity instanceof Alien) {
entity.y += 20;
renderAliens(entity, this.context);
}
}
}
endGame() {}
}
const newGame = new Game();
newGame.start();
newGame.render();
let t = setInterval(newGame.update, 1000);
You have two options:
.bind(). This binds this to the newGame instance
setInterval(newGame.update.bind(newGame), 1000);
setInterval(function(){
newGame.update();
}, 1000);
Just write the interval like:
const intervalRef = setInterval(() => { newGame.update() }, 1000);
Why don't you just declare the interval in your constructor? This way, you will avoid any context issues.
constructor() {
this.gameOver = false;
this.entities = [];
this.context = document.getElementById("canvas").getContext("2d");
setInterval(this.update.bind(this), 1000); // Here
}