Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 888
Carlos Barbosa Avatar asked Mar 31 '11 07:03

Carlos Barbosa


People also ask

How do you increment and decrement in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

How do you increment a variable in JavaScript?

If used postfix, with operator after operand (for example, x++ ), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x ), the increment operator increments and returns the value after incrementing.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

Which one will decrease the value of number by 1 in JavaScript?

Increment — x++ or ++x. Decrement — x-- or --x.


1 Answers

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>
like image 71
codingbadger Avatar answered Nov 03 '22 00:11

codingbadger