0

I have a constructor where I define a ListFactory and a function called Start, I don't know why if I'm not using a setInterval it works:

constructor(w = 800, h = 400) {
  super("imgs/bg.png", 0, 0, w, h, -5, 0);
  this.bird = new Bird();
  this.pipes = new ListFactory();
  this.score = 0;
}
start() {
  this.randomNumber=Math.floor(Math.random() * 250);
  window.addEventListener('keydown', event=> {
    this.bird.incrementHop();
  });
  this.pipes.push(new PipeC(150 + this.randomNumber)); 
}

But if I use a setInterval it doesn't work and it prints a "Cannot read property 'push' of undefined" error

constructor(w = 800, h = 400) {
  super("imgs/bg.png", 0, 0, w, h, -5, 0);
  this.bird = new Bird();
  this.pipes = new ListFactory();
  this.score = 0;
}
start() {
  this.randomNumber=Math.floor(Math.random() * 250);
  window.addEventListener('keydown', event=> {
    this.bird.incrementHop();
  });
  setInterval (function () {
    return this.pipes.push(new PipeC(150 + this.randomNumber));
  }, 2000);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jeral
  • 45
  • 4
  • Use an arrow function instead of `function()`, just like you did in `addEventListener()`. – Barmar May 18 '21 at 19:15
  • The return value of the `setInterval()` callback function isn't used. Why are you returning the result of `push()`? – Barmar May 18 '21 at 19:16

0 Answers0