在setInterval中执行this.function

时间:2017-10-15 17:44:11

标签: javascript

当我致电this.cycle时,我想每隔this.delay毫秒致电this.start。 当然,这不起作用:



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 个答案:

答案 0 :(得分:0)

我可以看到的一个问题是,计时器功能中的this不是您认为的那样。

所以要么

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

或只使用箭头功能

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