0

I want to call this.cycle every this.delay ms when I call this.start. Of course, this is not working :

function Timer(delay, repetitions){
  this.delay = delay;
  this.maxrep = repetitions;
  this.rep = 0;

  this.start = function(){
    this.interval = setInterval(function(){
      this.cycle();
    },this.delay);
  }

  this.cycle = function(){
    this.rep++;
    console.log(this.rep);
    if(this.rep >= this.max){
      clearInterval(this.interval);
    }
  }
}

1 Answers1

0

One issue I can see is that this inside the timer function is not the this you think it is.

So either

var me = this
this.start = function(){
  this.interval = setInterval(function(){
    me.cycle();
  },this.delay);
}

or just use an arrow function

this.start = function(){
  this.interval = setInterval(() => this.cycle(), this.delay);
}
Balázs Édes
  • 13,452
  • 6
  • 54
  • 89