如何修改JavaScript问卷代码实现单题30秒独立倒计时功能
修改后的完整代码
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; // 存储当前题目的计时器ID,方便切换时销毁 let timerId = null; 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() { // 切换题目时先销毁旧计时器 if(timerId) clearInterval(timerId); 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; // 每道题开始时重置倒计时为30秒 minuteur = 30; timer.textContent = minuteur; Array.from( target.childNodes ).forEach( child => target.removeChild( child ) ); const title = document.createElement('h1'); title.innerHTML = question.question; target.appendChild( title ); const timerEl = document.getElementById("timer"); // 创建新计时器,存到全局变量 timerId = setInterval(()=>{ if(minuteur>0){ decrementMinuteur(); timerEl.textContent = minuteur; } else { // 倒计时结束自动跳转到下一题 clearInterval(timerId); nextQuestion(); } },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();
核心改动说明
- 新增
timerId变量存储当前题目的计时器实例,切换题目或倒计时结束时先销毁旧计时器,避免多个计时器同时运行导致计时混乱 - 每次渲染新题目时将
minuteur重置为30,实现单题独立计时 - 倒计时归0时自动触发
nextQuestion切换到下一题,符合强制限时作答的要求
内容的提问来源于stack exchange,提问作者PitxRosalina Pitalina
相关产品推荐
相关产品推荐

