dmperkins74
dmperkins74

Reputation: 167

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>

Upvotes: 0

Views: 83

Answers (3)

Diamond
Diamond

Reputation: 598

You are giving the wrong parameter to the clearInterval function. clearInterval takes the variable that setInterval is assigned to. So in lieu of updateScore, you should write scoreTimer

clearInterval(scoreTimer);

In the case that you were giving that wrong parameter, clearInterval was not working properly and in fact, it was not clearing the previous setInterval variable. So, when you were pressing the button for the second time, scoreIncrement was again set to 10 and two setIntervals were working simultaneously to increment myScore. So your incrementing speed doubled. and when you were pressing it for the third time, your incrementing speed tripled and so forth.

Upvotes: 0

Jossef Harush Kadouri
Jossef Harush Kadouri

Reputation: 34207

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

Upvotes: 1

lucasjackson
lucasjackson

Reputation: 1525

You aren't clearing your interval properly. Try the following:

clearInterval(scoreTimer);

I've added some timing logs to verify as well.

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

function increaseScore() {
  scoreCountDown(10);
}


//SCORING
function scoreCountDown(scoreAmt) {
  scoreIncrement = scoreAmt
  console.time('timer');
  scoreTimer = setInterval(updateScore, 50);
}

//UPDATES SCORE on a Set Interval
function updateScore() {
  if (scoreIncrement > 0) {
    myScore += 1
    scoreText.innerHTML = "Score " + myScore;
    --scoreIncrement
  } else {
    console.timeEnd('timer');
    clearInterval(scoreTimer)
  }
}
<button onclick="increaseScore()">Add Score</button>
<br>
<span id="scoreText">000</span>

Upvotes: 0

Related Questions