Dlacrem
Dlacrem

Reputation: 71

Countdown with setInterval going too fast

could someone help me, I would like to know how to make it so the countdown doesn't go faster every time I click? I assume clear interval but not sure what I need to put. Thanks

var cD = 100;

function countDown() {
    if (cD > 0) {
        cD -= 1;
        $(".countdown").html(cD +"s");
    }
}

$(".countdown-trigger").click(function(){
    cD = 100;

    setInterval(countDown, 10);
});
.countdown-trigger {
    height: 50px;
    width: 100px;
    background-color: blue;
}

.countdown {
    font-family: "Teko", sans-serif;
    font-size: 100px;
    line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
    </div>
    <div class="countdown-trigger">
    </div>

Upvotes: 1

Views: 2105

Answers (2)

james
james

Reputation: 732

var cD = 100;
var myOtherVar;

function countDown() {
    if (cD > 0) {
        cD -= 1;
        $(".countdown").html(cD +"s");
    } else {
        clearInterval(myOtherVar);
    }
}

$(".countdown-trigger").click(function(){
    cD = 100;

    myOtherVar = setInterval(countDown, 10);
});
.countdown-trigger {
    height: 50px;
    width: 100px;
    background-color: blue;
}

.countdown {
    font-family: "Teko", sans-serif;
    font-size: 100px;
    line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown">
    </div>
    <div class="countdown-trigger">
    </div>

You're right. You just need to clear your interval. Every time you click the area it sets up another set of events that occur every 10ms & that is why it continues to get faster & faster.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you never clear the previous timeout on each successive click, hence after 3 clicks you have three timers all decrementing the value every 10ms.

To fix this call clearTimeout() when cD hits 0. Also note that you would need a mechanism to prevent starting multiple intervals while the previous one is still running, or else you'll have the same issue. To do that you can use a boolean flag. Try this:

var cD = 100, interval, running = false;

function countDown() {
  if (cD > 0) {
    cD -= 1;
    $(".countdown").html(('00' + cD).slice(-2) + "s");
  } else {
    clearInterval(interval);
    running = false;
  }
}

$(".countdown-trigger").click(function() {
  if (running)
    return;
    
  cD = 100;
  running = true;
  interval = setInterval(countDown, 10);
});
.countdown-trigger {
  height: 50px;
  width: 100px;
  background-color: blue;
}

.countdown {
  font-family: "Teko", sans-serif;
  font-size: 100px;
  line-height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="countdown"></div>
<div class="countdown-trigger"></div>

Upvotes: 3

Related Questions