javascriptcountdown

Javascript stop countdown


I have a countdown in js and I can't add a trick I would like.

When the counting ends, it does not stop. Negative numbers start and instead I would like it to stop at 0 once the time has expired. How can I?

  var counter = null;

  window.onload = function() {
    initCounter();
  };

  function initCounter() {
    // get count from localStorage, or set to initial value of 1000
    count = getLocalStorage('count') || 1000;
    counter = setInterval(timer, 1000); //1000 will  run it every 1 second
  }

  function setLocalStorage(key, val) {
    if (window.localStorage) {
      window.localStorage.setItem(key, val);
    }

    return val;
  }

  function getLocalStorage(key) {
    return window.localStorage ? window.localStorage.getItem(key) : '';
  }

  function timer() {
    count = setLocalStorage('count', count - 1);
    if (count == -1) {
      clearInterval(counter);
      return;
    }

    var seconds = count % 60;
    var minutes = Math.floor(count / 60);
    var hours = Math.floor(minutes / 60);
    minutes %= 60;
    hours %= 60;

    document.getElementById("countdown").innerHTML = hours +  " ore "  + minutes +  " min "   + seconds +  "  sec";
  }

Solution

  • The problem is that you were putting count with -1 value in LocalStorage.

    count = setLocalStorage('count', count - 1);
    

    And after page reload you kept subtracting 1 from -1 and you got -2, which your condition count == -1 couldn't catch. Solution is to put next count value in LocalStorage after you check if need to continue your timer or not.

    <script type="text/javascript">
    
      let count = 0;
      let counter = null;
    
      window.onload = function() {
        initCounter();
      };
    
      function initCounter() {
        // get count from localStorage, or set to initial value of 1000
        count = Number(getLocalStorage('count')) || 5;
        counter = setInterval(timer, 1000); //1000 will  run it every 1 second
      }
    
      function setLocalStorage(key, val) {
        if (window.localStorage) {
         window.localStorage.setItem(key, val);
        }
    
        return val;
      }
    
      function getLocalStorage(key) {
        return window.localStorage ? window.localStorage.getItem(key) : '';
      }
    
      function timer() {
        const nextCount = count - 1
        if (nextCount < 0) {
          clearInterval(counter);
          return;
        }
        count = setLocalStorage('count', nextCount);
    
        const seconds = count % 60;
        let minutes = Math.floor(count / 60);
        let hours = Math.floor(minutes / 60);
        minutes %= 60;
        hours %= 60;
    
        document.getElementById("timer").innerHTML = hours +  " ore "  + minutes +  " min "   + seconds +  "  sec";
      }
     </script>
     
    <div id="timer"></div>