【问题标题】:Decreasing The Timer Variable减少定时器变量
【发布时间】:2017-12-28 19:37:56
【问题描述】:

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

我在ts文件中的Start函数和Score函数如下:

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 函数只调用一次。如何减少这个时间变量?

【问题讨论】:

    标签: javascript angular typescript timer


    【解决方案1】:

    清除间隔并重新设置

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

    【讨论】:

    • 如果每次运行时都清除间隔,那么使用间隔是没有意义的。
    • 间隔在每次通过时都不会被清除,它在特定条件下清除,例如分数是 100、300 等
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2020-09-13
      • 2022-12-09
      • 2017-08-18
      相关资源
      最近更新 更多