【问题标题】:Why countdown timer suddenly executes fast?为什么倒数计时器突然执行得很快?
【发布时间】:2019-02-10 00:58:45
【问题描述】:

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

  • 倒计时
  • 问题
  • 问题选择

每个问题功能的倒数计时器工作正常如果回答按钮尚未点击,或者MqCheckAnswer功能尚未调用.

但是,当用户点击一个答案时,倒计时会突然快速执行。

它的延迟不是 1 秒,而是 0.3 秒。 IE。 5,4,3,2,1 调用MqCheckAnswer函数时输出: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);

}

【问题讨论】:

标签: android angular typescript ionic-framework ionic3


【解决方案1】:

我假设current 存储剩余时间。

您应该使用setInterval,而不是递归调用MqEachQuizTimer()。

另外,使用句柄(我称之为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
}

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

【讨论】:

  • 谢谢@danday74,我能够解决这个问题。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多