Search code examples
javascriptecmascript-6settimeout

Set Timeout not decrementing param value


I am trying to make my setTimeout function reusable. But whenever I pass the remainingTime value, It does not decrement.

console.log(remainingTime); repeatedly returns 99 rather than decrementing ie 98, 97.

Any ideas?

let remainingTimeToSolveQuiz = 100;
const timeRemainingEl = document.querySelector("#time-remaining");

function quizCountDown(remainingTime, elementToDisplayTime) {

  remainingTime--;
  console.log(remainingTime);

  if (remainingTime === 0) {
    // something
    clearTimeout(timer);
  }
  elementToDisplayTime.textContent = remainingTime;
}

let quizTimer = setInterval(quizCountDown, 1000, remainingTimeToSolveQuiz, timeRemainingEl);
<div>
Time: <span id="time-remaining"></span>
</div>


Solution

  • Your setInterval is calling the function every one second. Every time it is called you are passing the same params, one of which is a value of 100. So every time your function is called, you are passing 100 and your function does what it is asked to do, subtract 1. That is why you see 99 repeat.

    Solution: A global variable to keep track of the time:

    let quizTime = 100; // global variable stores the quiz time
    
    const timeRemainingEl = document.querySelector("#time-remaining");
    let quizTimer;
    
    function quizCountDown(elementToDisplayTime) {
    
      if (quizTime === 0) {
        // something
        clearTimeout(quizTimer);
      }
      elementToDisplayTime.textContent = quizTime;
      
      console.log(quizTime);
      quizTime--; // Calling this last starts your quiz timer with 100
    }
    
    quizTimer = setInterval(quizCountDown, 1000, timeRemainingEl);
    <div>
    Time: <span id="time-remaining"></span>
    </div>

    Also, it helps to call quizTime-- last. Because then your timer will show 100 initially.