skip to Main Content

I’m trying to write code for a timer in Javascript and would appreciate any help!
Here is my current code:

//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);

When I test the code and click on an incorrect answer the timer is still not decreasing by 10 seconds and I’m not sure why?! Any help would be fantastic! Thank you! I have tried removing

secondsLeft--;
    time.textContent = secondsLeft;

at the start of the function but then I can’t see the timer at all!

I want the timer to decrease by 10 seconds when an inncorrect option is chosen in a quiz.

2

Answers


  1. A better approach would be to start by declaring the time at which the timer expires, and reducing that end time by 10 seconds where necessary.

    Then, update the time remaining every second (or, if there is less than a second remaining, update the time exactly at the end time). By tracking the end time directly, you avoid a situation where the code takes time to run, and where that time ends up causing the total time to be unintentionally extended.

    I didn’t want to overcomplicate the code, but for more accuracy, specify that the setTimeout should happen such that it triggers exactly on a second boundary instead of simply 1 second in the future.

    let endTime = +new Date() + 60_000
    
    function updateTimer() {
      let msRemaining = Math.max(0, endTime - new Date())
      document.getElementById('remaining').textContent 
        = Math.round(msRemaining/1000) || 'done'
      if(msRemaining) setTimeout(updateTimer, Math.min(1000, msRemaining))
    }
    
    updateTimer()
    
    document.getElementById('btn').onclick = () => {
      endTime -= 10_000
      updateTimer()
    }
    <div id="remaining"></div>
    <button id="btn">-10s</button>
    Login or Signup to reply.
  2. It seems that the issue is because you’ve put the logic which handles whether or not the user selected the correct answer within the timer update handler.

    From the context, a better approach may be to have this within separate event handlers on the answers which add/subtract a separate variable which controls how much time is remaining in the quiz.

    Here’s a simplified example of this approach:

    const startButton = document.querySelector('#start');
    const quizContainer = document.querySelector('#quiz-container');
    const time = document.querySelector('#time');
    const rightButton = document.querySelector('#right-answer');
    const wrongButton = document.querySelector('#wrong-answer');
    
    const quizTimeSeconds = 10;
    let remainingTimeSeconds = 0;
    let countdownTimer;
    
    rightButton.addEventListener('click', () => {
      remainingTimeSeconds += 3;
      updateTimeUi();
    });
    
    wrongButton.addEventListener('click', () => {
      remainingTimeSeconds -= 3;
      updateTimeUi();
    }); 
    
    const startQuiz = () => {
      startButton.classList.add('hide');  
      quizContainer.classList.remove('hide');
      startCountdown();
      updateTimeUi();
    }
    
    const handleIntervalUpdate = () => {
      remainingTimeSeconds--;
      updateTimeUi();
      
      if (remainingTimeSeconds <= 0) {
        endQuiz();
      }
    }
    
    const endQuiz = () => {
      remainingTimeSeconds = 0;
      clearInterval(countdownTimer);
      startButton.classList.remove('hide');  
      quizContainer.classList.add('hide');
    }
    
    const updateTimeUi = () => {
      time.textContent = Math.max(0, remainingTimeSeconds);
    }
    
    const startCountdown = () => {
      remainingTimeSeconds = quizTimeSeconds;
      var countdownTimer = setInterval(handleIntervalUpdate, 1000);
    }
    
    startButton.addEventListener("click", startQuiz);
    .hide {
      display: none;
    }
    <button id="start">Start</button>
    
    <div id="quiz-container" class="hide">
      <p>
        <span id="time"></span>s remaining...
      </p>
      
      <button id="right-answer">Right Answer...</button>
      <button id="wrong-answer">Wrong Answer...</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search