Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

328
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!