jquery reset the timer on every click timer is working very fast

1590 views jquery
4

I have set the count down timer of 3 seconds when it is zero displays alert , when click on it again before setting it to 0 the timer is working very fast.

$(".change-word").click(function(e) {
    $(".countdown").html("0");
    $(".countdown").html("3");
    var doUpdate = function() {
        $('.countdown').each(function() {
            var count = parseInt($(this).html());
            if (count !== 0) {
                $(this).html(count - 1);
            } else {
                alert("zero");
            }
        });
    };
    setInterval(doUpdate, 1000);
});

This is the html

<div class="countdown">3</div>

answered question

2 Answers

10

When the timer hits 0 you do not:

  • Set a new value to the .countdown div
  • Stop the setInterval

This way it always loops every 1000ms, even if you do not click "Ok" on the alert, that's why it seems it goes "faster".

If you replace the alert with a console.log(count) you'll see it will write 0 every second.

$(".change-word").click(function(e) {
    $(".countdown").html("0");
    $(".countdown").html("3");
    var doUpdate = function() {
        $('.countdown').each(function() {
            var time = new Date().getMinutes() +":"+ new Date().getSeconds();
            console.log(time);
            var count = parseInt($(this).html());
            if (count !== 0) {
                $(this).html(count - 1);
            } else {
                console.log("zero");
            }
        });
    };
    setInterval(doUpdate, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown">3</div>
<button class="change-word">Go</div>

posted this
4

You need to clear interval on every click and when counter reaches 0. See this example:

let interval;
$(".change-word").click(function(e) {
  //$(".countdown").html("0");
  $(".countdown").html("3");
  clearInterval(interval);
  var doUpdate = function() {
    $('.countdown').each(function() {
      var count = parseInt($(this).html());
      if (count !== 0) {
        $(this).html(count - 1);
      } else {
        clearInterval(interval);
        alert("zero");
      }
    });
  };
  interval = setInterval(doUpdate, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="countdown">3</div>

<div class='change-word'>
  Change word
</div>

posted this

Have an answer?

JD

Please login first before posting an answer.