Skip to content
Advertisement

Increase and decrease a variable until a number is reached in Javascript

How can I increase and decrease a variable in Javascript until 100 and when 100 is reached it should start decreasing.

So accuracyBarValue should start in 0, increase to 100, and when 100 is reached it should go to 0, and then repeat procedure.

This in intervals of 10.

I use this in a very simple JS game, where this value is used to increase and decrease a PowerBar.

Advertisement

Answer

Here is another take on this:

var up = true;
var value = 0;
var increment = 10;
var ceiling = 100;

function PerformCalc() {
  if (up == true && value <= ceiling) {
    value += increment

    if (value == ceiling) {
      up = false;
    }
  } else {
      up = false
      value -= increment;

      if (value == 0) {
        up = true;
      }
  }

  document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />';
}
setInterval(PerformCalc, 1000);
<div id="counter"></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement