0

I have this jQuery function:

$(document).ready(function() {
  var timeVal = parseInt($('#timeMin').text());
  var mins = 60;
  $("#startbtn").click(function() {

    setInterval(time, 1000)
  });

  function time() {
    if (timeVal >= 0) {
      if (mins > 0) {
        if (mins <= 10) {
          console.log(mins - 1);
          $("#clock").html(timeVal + " : 0" + (mins - 1));
          mins -= 1;
        } else {
          console.log(mins);
          $("#clock").html(timeVal + " : " + (mins - 1));
          mins -= 1;
        }
      } else if (mins === 0) {
        timeVal -= 1;
        mins = 60;
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timeMin">
  1
</div>
<button type="button" id="startbtn">
start
</button>
<br><br>
<div id="clock">
  00:00
</div>

So it's supposed to execute every second once I click the button ('startbtn'). It's working fine. It goes to 00:00. However when I click it a second time it goes faster. Why does it do that.

PS. Here's the fiddle :

https://jsfiddle.net/8s25ezrq/1/

Thank you for your answers.

Diego Rios
  • 463
  • 1
  • 5
  • 18
  • 3
    Because you're now running the function on two intervals. You never canceled the first. –  Mar 14 '17 at 18:46
  • 1
    ^^ to do so, save its handle (`handle = setInterval(time, 1000)` with `handle` declared in a reasonable place) and when you want to cancel, `clearInterval(handle);` – T.J. Crowder Mar 14 '17 at 18:47
  • Yep, not _faster_-- just _more_. – Alexander Nied Mar 14 '17 at 18:47
  • Thanks for your answers! I don't really think it is a duplicate because I was asking the reason. I didn't really know it was calling multiple intervals. Thanks! – Diego Rios Mar 14 '17 at 18:48
  • @squint how do you embed that? – Diego Rios Mar 14 '17 at 18:51
  • One of the buttons above the edit area is for a "stack snippet", which gives you an interface similar to jsFiddle to embed a demo. Now when in edit mode, you'll see a `edit the above snippet` link below the demo that will let you update it. –  Mar 14 '17 at 18:52

1 Answers1

4

It's not going faster, there are multiple intervals running, so it appears faster. You are never clearing the original interval.

You need to set the interval to a variable and clear it each time the button is clicked, and then start a new one doing the same thing:

var myInterval;
$("#startbtn").click(function(){
  clearInterval(myInterval);
  myInterval = setInterval(time, 1000);
});
StephenRios
  • 2,192
  • 4
  • 26
  • 42
  • Would it work if I clear the interval once it gets to '00:00'? – Diego Rios Mar 14 '17 at 18:49
  • 1
    Or just don't run it again if `myInterval` is not `undefined`. Or maybe, use `.one` to bind the handler if there's no stop/start functionality. –  Mar 14 '17 at 18:50