I try to increase the value of a variable valuem from 0 to 10 and if the value of valuem is 10 it should decrease until the value is 0, then again increase until 10 and so on.
for example: 0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1 0 1 2 ...
what is the simplest and efficientest way to do that?
var valuem = 0;
$('#number').text(valuem);
function count() {
valuem++;
$('#number').text(valuem);
if (valuem == 10) {
valuem--;
$('#number').text(valuem);
}
}
setInterval(count, 1000);
This way:
var valuem = 0, dir = 1;
$('#number').text(valuem);
function count() {
valuem += dir;
$('#number').text(valuem);
if (valuem < 1) dir = 1;
if (valuem > 9) dir = -1;
}
setInterval(count, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="number"></div>
You have to store the counting direction as the part of the state besides the current number to know in which direction to count when valuem is between 1 and 9.
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