dmperkins74 dmperkins74 - 5 months ago 22
Javascript Question

Speedy setInterval

I'm trying out setInterval (first time) to increase a score and it's working great, except that for some reason it keeps speeding up.

In the sample below, every time I click the button, the score increases more quickly. It's like the 50 is decreasing, why?

Any help appreciated, thanks.



var scoreTimer;
var myScore = 0;
var scoreIncrement = 0;

function increaseScore() {
scoreCountDown(10);
}


//SCORING
function scoreCountDown(scoreAmt) {
scoreIncrement = scoreAmt
scoreTimer = setInterval(updateScore, 50);
}

//UPDATES SCORE on a Set Interval
function updateScore() {
if (scoreIncrement > 0) {
myScore += 1
scoreText.innerHTML = "Score " + myScore;
--scoreIncrement
} else {
clearInterval(updateScore)
}
}

<button onclick="increaseScore()">Add Score</button>
<br>
<span id="scoreText">000</span>




Answer

It's because clearInterval wasn't called properly. To fix that, change

clearInterval(updateScore)

to

clearInterval(scoreTimer)

view it online - https://plnkr.co/edit/0xmFC3rN5jciroYPjHtQ?p=preview