我正在做一个测验,现在遇到了下一个问题,我的计时器很奇怪。...例如它从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--;
}
}
答案 0 :(得分:0)
真的很接近!只是您的间隔没有被清除,因为引用错误:
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
。