Как я могу сбросить свой SetInterval при переходе к следующему вопросу? - PullRequest
0 голосов
/ 24 января 2019

Я строю тест, и теперь при переходе к следующему вопросу у меня возникает проблема, что мой таймер работает странно ... он прыгает, например, с 4 до 9, а затем на 3, но я хочу, чтобы он перешел к 10 снова и просто отсчет до 0 и перейти к следующему вопросу. Может ли кто-нибудь объяснить мне это? Или лучше использовать SetInterval? Буду признателен, если вы поможете мне с этим!

var currentQuestion = 0;
var currentCount = 0;
var maxCount = 3;
var totalScore = 0;

function displayQuestion() {
  var question = allQuestions[currentQuestion].question;
  var showQuestion = $(document).find(".question-full");

  var showQuestionImage = $(document).find(".questions-img");
  var questionImage = allQuestions[currentQuestion].questionImg;

  var numAnswers = allQuestions[currentQuestion].responses.length;
  var answerList = $(document).find(".answers-buttons");

  /// SCORE
  var scoreCounter = $(document).find(".scoreCounter");

  $(showQuestion).text(question);
  $(showQuestionImage).html(questionImage);

  $(answerList).find("li").remove();
  $(scoreCounter).find("span").remove();
  $('.result-container').find("h2").remove();
  $('.result-container').find("img").remove();
  $('.result-container').find("a").remove();

  $('<span>'+ totalScore +'</span>').appendTo(scoreCounter);

  var answers;
  var score;
  for(var i = 0; i < numAnswers; i++) {
    answers = allQuestions[currentQuestion].responses[i].text;
    score = allQuestions[currentQuestion].responses[i].score;
    $('<li><button class="nextButton" data-score="'+ score +'" type="button">'+answers+'</button></li>').appendTo(answerList);
  }

  nextQuestion();


  $(".nextButton").on("click", function () {
    var score = $(this).data('score');
    IncreaseScore();

    currentQuestion++;

    totalScore += score;

    if (currentQuestion < allQuestions.length) {
        displayQuestion();
    } else {
      $('.after-container').fadeIn('slow');
      $('.content').fadeOut('slow');
    }
  });
}


function nextQuestion() {
  var tijd = 10;
  var interval = setInterval(function() {
    tijd--;
    document.getElementById("countdowntimer").textContent = tijd;
    if(tijd == 0) {
      currentQuestion++;
      displayQuestion();
      console.log(tijd);
      clearInterval(tijd);
    }
  }, 1000);
}

function IncreaseScore() {

  currentCount++;

  if (currentCount > maxCount) {
    currentCount--;
  }
}

1 Ответ

0 голосов
/ 24 января 2019

Действительно близко!Просто ваш интервал не очищается, так как есть неправильная ссылка:

function nextQuestion() {
  var tijd = 10;
  var interval = setInterval(function() {
    ...
      clearInterval(tijd);
    ...
  }, 1000);
}

должно быть

function nextQuestion() {
  var tijd = 10;
  var interval = setInterval(function() {
    ...
      clearInterval(interval);
    ...
  }, 1000);
}

С вашей реализацией все в порядке, просто у вас все интервалы были бы ещеработает до 0 и обновляет #countdowntimer любым последним в секунду.

...