Search code examples
javascripthtmlcsscleartimeout

clearTimeout() not clearing timer


function countDown(secs,elem)
{   
    var element = document.getElementById(elem);
    element.innerHTML = "Game ends in " + secs + " seconds!";
    if(secs<1)
    {   
        clearTimeout(timer);
        document.getElementById('gameContent').style.display='none';

    }
    secs--;
    var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);

}

 <div class="timerCount" id="status"></div>
 <script>countDown(5,"status");</script>

My timer starts correctly at 5 secs and decrements. My game div hides after the timer reaches 0 but the timer doesnt clear out and end instead it goes to negative. Please my bug in my code so as to stop the timer and clear it


Solution

  • It's more efficient if you just use setInterval and do something like this:

    function countDown(secs, elem) {
      var interval;
      var element = document.getElementById(elem);
      var timer = setInterval(function() {
        secs--;
        update();
        if (secs < 1) {
          clearInterval(timer);
        }
      }, 1000);
    
      function update() {
        if (secs > 0) {
          element.innerHTML = "Game ends in " + secs + " seconds!";
        } else {
          document.getElementById('gameContent').style.display = 'none';
        }
      }
      update();
    
    }
    
    countDown(5, "status");
    <div id="gameContent">
      <h1>Game</h1>
      <div class="timerCount" id="status"></div>
    </div>