vue. js, setTimeout мешает моему простому обратному отсчету - PullRequest
0 голосов
/ 12 июля 2020

Я упростил свой код, чтобы прояснить проблему, на этой странице vue в течение десяти секунд отображается вопрос, и ученик должен сказать ответ до того, как он появится, но вот проблема: у меня есть следующая кнопка, которая показывает следующий вопрос, считайте, что осталось 5 секунд, и вы нажимаете следующую кнопку, а затем обратный отсчет полностью разрывается, даже он показывает минусовые цифры!

<template>
  <div class="container text-center">
      <div v-if = "showQuestion">
     <span> {{ question }} </span>
      <span style="color:red;"> &nbsp;&nbsp;&nbsp;{{ countDown }} </span>

    </div>

    <div v-if = "showAnswer">
            <p> {{ answer }} </p>
    </div>

    <div>
       <button class="btn btn-success" @click="next">next question </button>
         
    </div>
     
  </div>
</template>

<script>
export default {
     data(){
        return{
            questions: ['question1', 'question2', 'question3', 'question4', 'question5'] ,   
            answers: ['answer1', 'answer2', 'answer3', 'answer4', 'answer5'],
           
            question: '',
            answer: '',
           mayVar: null, //controlls setTimeout
            index : 0, 
             showQuestion: true,
             showAnswer: false,
              countDown : 10,           
            
        }
    },
    methods:{
        
            startQuiz(){
               this.countDown = 10;
               this.question = this.questions[this.index];
               this.answer = this.answers[this.index];
               this.countDownTimer();
               this.show();
              
            },

            show(){                
                 this.myVar =  setTimeout(() => { //question fades away and answer shows up
                       this.showQuestion = false;
                       this.showAnswer = true;

                    }, 10000);
            },

             next(){
                  clearTimeout(this.myVar); // 
                 this.index++;// goes to next question
                   this.showQuestion = true;
                 this.showAnswer = false;
                this.startQuiz();
                
             },
                 
             countDownTimer() {
                  
                if(this.countDown > 0) {
                    setTimeout(() => {
                        this.countDown--;
                        this.countDownTimer();
                    }, 1000);
                }
            },
    },

    created(){
      this.startQuiz();
    }
}
</script>

<style>

</style>

спасибо

вот ссылка на jsfiddle

1 Ответ

0 голосов
/ 12 июля 2020

Вы также должны очистить таймер обратного отсчета, когда нажмете «Далее». См. Фрагмент ниже.

const app = new Vue({
el: "#app",
data(){
        return{
            questions: ['question1', 'question2', 'question3', 'question4', 'question5'] ,   
            answers: ['answer1', 'answer2', 'answer3', 'answer4', 'answer5'],
           
            question: '',
            answer: '',
           mayVar: null, //controlls setTimeout
            index : 0, 
             showQuestion: true,
             showAnswer: false,
              countDown : 10,   
              count_down_timer: null // controls count down timer
            
        }
    },
    methods:{
        
            startQuiz(){
               this.countDown = 10;
               this.question = this.questions[this.index];
               this.answer = this.answers[this.index];
               this.countDownTimer();
               this.show();
              
            },

            show(){                
                 this.myVar =  setTimeout(() => { //question fades away and answer shows up
                       this.showQuestion = false;
                       this.showAnswer = true;

                    }, 10000);
            },

             next(){
                  clearTimeout(this.myVar); // 
                  clearTimeout(this.count_down_timer)
                 this.index++;// goes to next question
                   this.showQuestion = true;
                 this.showAnswer = false;
                this.startQuiz();
                
             },
                 
             countDownTimer() {
                  
                if(this.countDown > 0) {
                    this.count_down_timer = setTimeout(() => {
                        this.countDown--;
                        this.countDownTimer();
                    }, 1000);
                }
            },
    },

    created(){
      this.startQuiz();
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="container text-center">
      <div v-if = "showQuestion">
     <span> {{ question }} </span>
      <span style="color:red;"> &nbsp;&nbsp;&nbsp;{{ countDown }} </span>

    </div>

    <div v-if = "showAnswer">
            <p> {{ answer }} </p>
    </div>

    <div>
       <button class="btn btn-success" @click="next">next question </button>
         
    </div>
     
  </div>
</div>
...