Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
JavaScript this issue with SetInterval

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

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You have two options:

  • use .bind(). This binds this to the newGame instance
    setInterval(newGame.update.bind(newGame), 1000);
    
  • define a callback function:
    setInterval(function(){
      newGame.update();
    }, 1000);
    
about 4 years ago · Juan Pablo Isaza Relatório

0

Just write the interval like:

const intervalRef = setInterval(() => { newGame.update() }, 1000);
about 4 years ago · Juan Pablo Isaza Relatório

0

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
  }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda