Search code examples
javascripttimer

JS - it dosen't count zero second in a timer


let second = 2 // Make more realistic instead of 60
let minute = 1
let mytimer = setInterval(function(){
  let timer = second--
  console.log(minute + ':' + timer)
  if(second==0){
    second = 59
    minute--
  }
  if(minute==0){
    clearInterval(mytimer);
  }
},10)

As you can see, it's quite simple code, but there is a weird bug in there. my timer doesn't count second 0. When the timer gonna end, it'll stop at 0:01. it works perfectly by itself, but when it reaches 1:00 or 0:00 it entirely ignores 0 and jumps from 1:01 to 0:59. I also tried this solution, but it doesn't work too. what do I suppose to do now? (btw my previous questions weren't good enough, and I hope I could've to reach a better explanation this time)


Solution

  • Your code is stopping when min is 0, not when min and sec is zero. You need to change up your logic to account for that.

    let second = 0;
    let minute = 2;
    
    let mytimer = setInterval(function() {
      second--;
      if (second === 0 && minute === 0) {
        clearInterval(mytimer);
      } else if (second < 0) {
        second = 60 + second;
        minute--;
      }
    
      console.log(minute + ':' + second.toString().padStart(2, '0'))
    
    }, 1000)

    Now setInterval is NOT accurate. It will float. So it is better to use the a timestamp and get the difference.

    function msToTime(ms) {
      const seconds = Math.floor((ms / 1000) % 60).toString().padStart(2, '0');
      const minutes = Math.floor((ms / (1000 * 60)) % 60).toString().padStart(2, '0');
      
      return `${minutes}:${seconds}`;
    }
    
    const countDownTime = (outElem, ms) => {
      const endTS = Date.now() + ms;
      let timer;
      
      const display = text => outElem.textContent = text;
    
      const countDown = () => {
        const diff = endTS - Date.now();
        if (diff < 0) {
          display("00:00");
          window.clearTimeout(timer);
          return;
        }
    
        const ts = msToTime(diff);
        display(ts);
      };
    
      countDown();
      window.setInterval(countDown, 10);
    
    };
    
    countDownTime(document.querySelector('#out'), 2*60*1000);
    <div id="out"></div>