首页 > 解决方案 > 为什么倒数计时器突然执行得很快?

问题描述

我目前正在开发一个测验应用程序,我现在需要的是显示一个

如果尚未单击答案按钮,或者尚未调用MqCheckAnswer函数,则每个问题函数的倒数计时器工作正常。

然而,当用户点击一个答案时,倒数计时器突然快速执行。

它的延迟不是 1 秒,而是 0.3 秒。IE。调用MqCheckAnswer函数时输出 5,4,3,2,1 :5,3,2,0

谁能帮我解决这个问题?

.html 文件

<div *ngIf="MqQuizIsActivate">
<div class="progress">
    {{ current }}
</div>
<ion-row no-padding>

        <ion-col col-6 *ngFor="let data of MqlocalQuizData[MqActiveQuestion].QuesChoices">
            <button ion-button color="light" class="B_pclass_choices" (click)="MqCheckAnswer(data)">{{data.Choices}} </button>                                                    
        </ion-col>

</ion-row>
</div>

ts文件

//Setup the Quiz
MqSetQuiz() {
  if(this.MqQuizIsActivate){

      if(this.MqActiveQuestion != this.MqlocalQuizData.length){
          // Timer for each Question
          this.current = this.MqlocalQuizData[this.MqActiveQuestion].eaQuesTimer;
          this.MqEachQuizTimer(); 
      }
      else {
      this.MqQuizIsActivate = false;
      this.MqSetQuiz();
      }
  }    
}


//When answer button is clicked
MqCheckAnswer(data){
      if (data.correct) {
          this.MqCorrectAnswer++;
      }
          this.MqActiveQuestion++;
          this.MqSetQuiz();
    }



//Timer for Each Question
MqEachQuizTimer(){
setTimeout(() => {

    if(this.current != 0) {
        this.current--;           
        this.MqEachQuizTimer();
      }
      else {

        this.MqActiveQuestion++;
        this.MqSetQuiz();

      }
}, 1000);

}

标签: androidangulartypescriptionic-frameworkionic3

解决方案


我假设current存储剩余的时间量。

而不是MqEachQuizTimer()递归调用,你应该使用setInterval.

this.interval另外,当问题被这样回答时,使用句柄(我称之为)来清除间隔:

MqEachQuizTimer() {
  this.interval = setInterval(() => {
    this.current--;
  }, 1000)
}

MqCheckAnswer(data) {
  if (data.correct) {
      this.MqCorrectAnswer++;
  }
  this.MqActiveQuestion++;
  this.MqSetQuiz();
  clearInterval(this.interval) // this will stop the timer
}

这可能不是您想要做的,但它应该让您沿着正确的路线前进。


推荐阅读