I'm currently working on a quiz app, What i need for now is to display a
The countdown timer for Each Question function works fine IF the answer button is not yet clicked or rather the MqCheckAnswer function is not invoke yet.
However, when user clicks an answer, the countdown timer suddenly executes fast.
Instead of a 1 second delay, its delay is like 0.3seconds. ie. 5,4,3,2,1 output when MqCheckAnswer function is invoked: 5,3,2,0
Can anyone help me in fixing this issue?
html file
<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 file
//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);
}
I assume current stores the amount of time remaining.
Rather than calling MqEachQuizTimer() recursively you should use setInterval.
Also, use a handle (I've called it this.interval) to clear the interval when the question is answered like this:
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
}
This may not be exactly what you want to do but it should set you along the right lines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With