I want to create a countdown timer for a quiz that will reset on the next question and also go to the next question if the time runs out and the player has not chosen a answer. Can anyone help me create this plz?
var counter = 10;
setInterval(function () {
counter--;
if (counter >= 0) {
id = document.getElementById('count');
id.innerHTML = counter;
}
if (counter === 0) {
id.innerHTML = 'Times Up!';
}
}, 1000);
'''
Here is the basic working code for you. Play around with it to get your desired result. Happy coding!
var counter = 10; //Time counter
var questionsCount = 0; //Questions counter
//Questions array
var questions = [
"Question 1","Question 2","Question 3"
]
questionDivId = document.getElementById('question');
setInterval(function () {
counter--;
if (counter >= 0) {
id = document.getElementById('count');
id.innerHTML = counter;
}
if (counter === 0) {
id.innerHTML = 'Times Up!';
counter = 10;
questionsCount++;
}
//To check if all questions are completed or not
if (questionsCount === questions.length){
questionDivId.innerHTML = "Well Played! Game is over";
id.innerHTML = "";
} else{
questionDivId.innerHTML = questions[questionsCount];
}
}, 1000);
//To go to the next question
function goToNextQuestion() {
questionsCount++;
counter = 10;
}
<div>
<h1 id="question"></h1>
<h1 id="count"></h1>
<button onclick="goToNextQuestion()">Next</button>
</div>