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="ΠΠ°ΠΆΠΌΠΈ ΠΌΠ΅Π½Ρ" />