Why does the timer stop after 2 seconds left to 0?

<script> function timer(tag, sec) { document.getElementById(tag).innerHTML = (sec / 60 >> 0) + 'min' + sec % 60 + 'sec' + '<br>'; sec -= 1; if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) { setTimeout(function() { timer(tag, sec); }, 1000); } else { document.getElementById(tag).innerHTML= "Time is over!"; } } </script> <div id="str"></div> <input type="button" onclick="timer('str', 5)" value="НаТми мСня" /> 

    2 answers 2

    Enough sec -= 1; move where necessary

     function timer(tag, sec) { document.getElementById(tag).innerHTML = (sec / 60 >> 0) + ' min ' + sec % 60 + ' sec' + '<br>'; if((sec / 60 >> 0) != 0 || (sec % 60) != 0) { setTimeout(function() { timer(tag, sec); }, 1000); sec -= 1; } else { document.getElementById(tag).innerHTML= 'Time is over!'; } } 
     <div id='str'></div> <input type='button' onclick='timer("str", 5)' value='НаТми мСня'> 

      Obviously because you set this behavior in the script. See:

      • press the button - timer is called with a value of 5
      • in timer value 5 is displayed in the div
      • subtract 1 from sec argument
      • set the timer to restart the timer function after 1 second, with a value of 4
      • triggered div set to 4
      • all this is repeated until the timer is called with argument 1, in which case restart will not occur, the div will first write 1 , and immediately the text "Time is over!".

      Thus, the timer is triggered 4 times, and each time we get such changes in the div :

      • four
      • 3
      • 2
      • 1, and immediately "Time is over!"

      A slightly edited version with the correct counter:

       function timer(tag, sec) { var el = document.getElementById(tag); if (sec > 0) { el.innerHTML = (sec / 60 >> 0) + ' min ' + sec % 60 + ' sec'; setTimeout(function() { timer(tag, sec); }, 1000); sec -= 1; } else { el.innerHTML= "Time is over!"; } } 
       <div id="str"></div> <input type="button" onclick="timer('str', 5)" value="НаТми мСня" />