减少计时器变量

时间:2017-12-28 11:25:38

标签: javascript angular typescript timer

此示例程序在单击按钮并在屏幕上连续打印乐谱变量时,在1000ms内启动计时器。当分数变为100时,我希望计时器在500毫秒内运行。当分数变为300时,我希望定时器在250ms内运行。

ts文件中的我的启动功能和分数功能如下:

public ScoreNumber: number = 0;
public TimeOfScore;
public Start() {
    this.TimeOfScore= setInterval(() => {
        this.Score();
    }, 1000);

public Score(){
ScoreNumber++;
}

使用html文件中的按钮启动函数调用。屏幕上的分数打印如下:

<div>{{Score}}</div>

我改变了代码:

public ScoreNumber: number = 0;
public TimeOfScore;
public time:number=1000;
public Start() {
    this.TimeOfScore= setInterval(() => {
        this.Score();
    }, time);

public Score(){
ScoreNumber++;
if(this.ScoreNumber>100&&this.ScoreNumber<300){
this.time=500;
}
else if(this.ScoerNumber>300){
this.time=250;
}    
}

当然,代码没有按照我的意愿运行。因为Start函数只调用一次。如何减少这个时间变量?

2 个答案:

答案 0 :(得分:0)

清除间隔并重新设置

if(this.ScoreNumber>100&&this.ScoreNumber<300){
this.time=500;
this.restartInterval();
}
else if(this.ScoerNumber>300){
this.time=250;
this.restartInterval();
} 

重启间隔功能

restartInterval()
{
    clearInterval(this.TimeOfScore);
    this.TimeOfScore= setInterval(() => {
        this.Score();
    }, this.time);
}

答案 1 :(得分:0)

1)只使用递归的setTimeout 2)遵循javascript约定!

 private scoreNumber: number = 0;
 private duration: number = 1000;
 private running = false;

 public start(){
   if(this.running) return;
   this.running = true;
   run();
 }

 private run(){
   this.scoreNumber++;
   if(this.scoreNumber > 100 && this.scoreNumber < 300){
     this.duration = 500;
   } else if(this.scoreNumber > 300){
     this.duration = 250;
   } 
   setTimeout(run, this.duration);
}