在Javascript中,如果输入了错误的选项,如何让计时器减少10秒?

问题描述 投票:0回答:1

我正在尝试用 Javascript 编写计时器代码,希望得到任何帮助! 这是我当前的代码:

//Timer Function

function setTime() {
  var timerInterval = setInterval(function () {
    secondsLeft--;
    time.textContent = secondsLeft;
    if (currentQuestion.answer !== selectedOption) {
      secondsLeft -= 10;
      time.textContent = secondsLeft;
    }

    if (secondsLeft === 0) {
      clearInterval(timerInterval);
      endQuiz();
    }
  }, 1000);
}

startButton.addEventListener("click", setTime);

当我测试代码并单击错误答案时,计时器仍然没有减少 10 秒,我不知道为什么?!任何帮助都会很棒!谢谢你!我试过删除

secondsLeft--;
    time.textContent = secondsLeft;

在函数开始时,但我根本看不到计时器!

当测验中选择了不正确的选项时,我希望计时器减少 10 秒。

javascript function timer
1个回答
0
投票

更好的方法是首先声明计时器到期的时间,并在必要时将结束时间缩短 10 秒。

然后,每秒更新剩余时间。通过直接跟踪结束时间,您可以避免代码需要时间才能运行的情况,以及该时间最终导致总时间无意延长的情况。

let endTime = +new Date() + 60_000

function updateTimer() {
  let secondsRemaining = Math.max(0, Math.round((endTime - +new Date())/1000))
  console.log(secondsRemaining)
  document.getElementById('secondsRemaining').textContent = secondsRemaining || 'done'
  if(secondsRemaining) setTimeout(updateTimer, 1000)
}

updateTimer()

document.getElementById('btn').onclick = () => {
  endTime -= 10_000
  updateTimer()
}
<div id="secondsRemaining"></div>
<button id="btn">-10s</button>

© www.soinside.com 2019 - 2024. All rights reserved.