当我致电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);
}
}
}

答案 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);
}