Javascript. Why is the timer breaking up early?



  • Why is the timer ruptured after 2 seconds to 0?

    <script>
    function timer(tag, sec) { 
    
    document.getElementById(tag).innerHTML = (sec / 60 &gt;&gt; 0) + 'min' + sec % 60 + 'sec' + '&lt;br&gt;'; 
    sec -= 1;
    
    if ((sec / 60 &gt;&gt; 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="Нажми меня" />



  • Obviously, because you put that behavior in the violin. Look:

    • We press the button. timer value 5
    • Total timer value 5 div
    • We' 1 of the argument. sec
    • We the timer for the reset of the function. timer 1 second, 4
    • response div fixed in 4
    • It's all over again while f-y timer will not be raised with argument 1, in which case there will be no reset, in div I'll sign it first. 1and immediately the text "Time is over!"

    The timer thus works four times, and every time such changes are received div:

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

    A slightly edited version with an adjustment 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="Нажми меня" />




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2