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.
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.
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.
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.
Increment — x++ or ++x. Decrement — x-- or --x.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With