android - 为什么倒数计时器突然执行得很快?
问题描述
我目前正在开发一个测验应用程序,我现在需要的是显示一个
- 倒计时器
- 问题
- 问题选择
如果尚未单击答案按钮,或者尚未调用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);
}
解决方案
我假设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
}
这可能不是您想要做的,但它应该让您沿着正确的路线前进。
推荐阅读
- python - Python:对 2d ndarray 进行排序并返回元组中的索引列表
- swift - UIDatePicker的变年箭头的动画过渡
- python - 手动查找质心和标记数据点之间的距离
- javascript - 如何使用`ws`库将此请求发送到websockets
- c - 即使我在顶部写了 char 答案,为什么我仍然第一次使用此函数错误?
- sendgrid - SendGrid 电子邮件活动 API 速率限制
- python - ValueError:没有为任何变量提供梯度 - Tensorflow 2.0
- makefile - Makefile 没有规则来制作所有人都需要的目标 index.html?
- latex - LaTeX 上的技能点表示
- php - 我们如何使用 ,'suppress_filters' = false 来查询 learnpress 或任何其他翻译方式?(使用 wpml 进行翻译)