Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

327
Vistas
setInterval setting this to window instead of class (calling class function)
render() {
    drawRect(0,0,canvas.width,canvas.height,3);
    console.log(this) // when called with setInterval(classObject.render, 1000), returns window; if called with (classObject).render returns (classObject)
    for (let i = 0; i <= this.sprites.length; i++) {
        if (this.sprites[i]) {
            let cs = this.sprites[i]
            cs.drawRoutine(cs.position.x,cs.position.y);
        }
    }
}
setRenderInterval(fps) {
    setInterval(this.render,1000/fps);
}

Here, let's assume classObject is called game. When game.render() is called normally, it has game as this. But when it's called using setInterval, it has window as this. How can I circumvent this? this.sprites is an array of sprites for the game, and it needs to be accessed using this, as there can be multiple games with different variable names. And cs.drawRoutine is a function within the sprite that just draws in the canvas. The function runs when normally called.

As requested (and because this is going to be open source later), here's the whole class and the thing that calls it:

class gameController extends instance {
constructor(name="untitled") {
    super(name);
    this.camera = null;
    this.rendering = {"FPS":0,"cnv":null,"ctx":null}
    this.sprites = [];
    this.data.renderFrame = 0;
}
render() {
    drawRect(0,0,canvas.width,canvas.height,3);
    for (let i = 0; i <= this.sprites.length; i++) {
        if (this.sprites[i]) {
            let cs = this.sprites[i]
            cs.drawRoutine(cs.position.x,cs.position.y);
        }
    }
}
setRenderInterval(fps) {
    return setInterval(this.render,1000/fps);
}

}

const game = new gameController("game");
game.setRenderInterval(30); // called from script/devconsole
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda