Home > Blockchain >  Condition with counter in timer
Condition with counter in timer

Time:10-09

So I have been trying to make like a timer type thing to count from 0 to 5 (one number up every sec, like normal timer) then stopping at 5 but It's not stopping at 5. What did I do wrong?

var licz = 0;

function timer() {
  window.setInterval(
    function() {
      document.getElementById('timer_r').innerHTML = licz;
      licz  ;
      if (licz >= 5) {
        window.clearInterval(timer);
      }
    }
    , 1000
  );
}
<input type="button" id="timer" on value="timer" onclick="timer();">
<p>Odliczanie: <span id='timer_r'> _ </span></p>

CodePudding user response:

Declare "timer" as a variable, like so:

let timer = setInterval(function(){
  document.getElementById('timer_r').innerHTML = licz;
  licz  ;
 }, 1000
)
if (licz >= 5) {
 clearInterval(timer)
}

This is because when you declare timer as a function, it is a separate function rather than an interval. You would have to call timer and create a loop, instead of just a normal interval.

CodePudding user response:

setInterval returns an integer ID corresponding to the timer.

This id can be supplied to clearInterval to stop the timer.

In your code you are supplying the function timer to clearInterval, meaning the timer is never cancelled.

let licz = 0, intervalId = null;

function timer() {
  intervalId = window.setInterval(
    function() {
      document.getElementById('timer_r').innerHTML = licz;
      licz  ;
      if (licz > 5) {
        window.clearInterval(intervalId);
      }
    }
    , 1000
  );
}
<input type="button" id="timer" on value="timer" onclick="timer();">
<p>Odliczanie: <span id='timer_r'> _ </span></p>

CodePudding user response:

What you need to be doing is complete your conditional like:-

        <script>

    var licz = 0;
    function timer() {
    window.setInterval(
        function(){
            document.getElementById('timer_r').innerHTML = licz;
    
    if (licz < 5) {
        licz  ;
    } else {
        window.clearInterval(timer);
    }

   
}, 1000);  
}

</script>
<br>    
<input type = "button" id = "timer" on value = "timer" onclick="timer();">
<p>Odliczanie: <span id = 'timer_r'> _ </span></p>

  • Related