Search code examples
jquerysetintervalcountdownclearinterval

Jquery stop countdown when reaches 0 with ClearInterval()


Hello I've made a countdown that counts from 5 to 0, but I want to counter be stopped at 0. I used the .stop() function but that didn't worked for me. I am refresing the countdown every second with SetInterval(). Now I'm trying to use ClearInterval() so the counter should stop with counting. I'm not sure but I think I'm using the ClearInterval totally wrong...

This is what I use:

if (time === 0) {
  clearInterval();
} 

Here is the code:

$(document).ready(function() {
  $("button").click(function() {
    var time = 5;
    setInterval(function() {
      time--;
      $('#time').html(time);
      if (time === 0) {
        clearInterval();
      }
    }, 1000);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time">5</div>
<button>Activate Countdown</button>


Solution

  • You need to tell clearInterval() which timer to stop. Assign the interval to a variable and then give that variable to clearInterval()

    $(document).ready(function() {
      $("button").click(function() {
        var time = 5;
        var timer = setInterval(function() {
          time--;
          $('#time').html(time);
          if (time === 0) {
            clearInterval(timer);
          }
        }, 1000);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="time">5</div>
    <button>Activate Countdown</button>