I have created a questionnaire where the user can answer the different questions in "text box". I tried to add a 30 second timer so that the user is forced to answer the different questions within the allotted time. But my timer is 30 seconds for ALL QUESTIONS, while I want it to be 30 seconds PER QUESTION. Can you help me do this please?
const questions = [
{
question: 'hello',
answers: 'hello',
points: 1
},
{
question: 'cc',
answers: 'cc',
points: 1
},
{
question: 'hi',
answers: 'hi',
points: 1
}
];
function *questionsGenerator( questions ) {
yield* questions;
}
const questionaire = ( query, nextButton, target, onCompleted ) => {
let score = 0;
let iterator = questionsGenerator( query );
let question = null;
let selectedAnswer = -1;
let minuteur = 30;
nextButton.addEventListener('click', nextQuestion);
function evaluateAnswer() {
if (!question) {
return;
}
if (selectedAnswer < 0) {
return;
}
if (question.answers === selectedAnswer) {
score += question.points;
}
return;
}
function decrementMinuteur(){
minuteur--
}
function nextQuestion() {
evaluateAnswer();
question = iterator.next();
if (question.done) {
nextButton.removeEventListener('click', nextQuestion);
onCompleted( score );
return;
}
question = question.value;
drawUI();
}
const timer = document.createElement('span');
timer.setAttribute("id", "timer");
document.body.appendChild(timer)
function drawUI() {
nextButton.setAttribute('disabled', true);
selectedAnswer = -1;
Array.from( target.childNodes ).forEach( child => target.removeChild( child ) );
const title = document.createElement('h1');
title.innerHTML = question.question;
target.appendChild( title );
const timer = document.getElementById("timer");
let id = setInterval(()=>{
if(minuteur>0){
decrementMinuteur();
timer.textContent = minuteur;
}
},1000)
const el = document.createElement('input');
el.type = 'text';
el.name = 'answer';
el.value = '';
el.id = 'answer';
el.addEventListener('change', () => {
selectedAnswer = el.value.trim();
} );
el.addEventListener('keydown', () => {
nextButton.removeAttribute('disabled');
} );
const container = document.createElement('div');
container.appendChild(el);
target.appendChild(container);
el.focus();
}
return {
nextQuestion
}
};
questionaire(
questions,
document.querySelector('#btnNext'),
document.querySelector('#questionaire'),
score => alert('You scored ' + score )
).nextQuestion();
This is related to me earlier question Create a questionnaire Javascript with "text box"
questionnaire