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);
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);
Share
Improve this question
edited Apr 24, 2016 at 12:44
Tamas Hegedus
30k12 gold badges66 silver badges101 bronze badges
asked Apr 24, 2016 at 12:41
klamertdklamertd
1033 silver badges16 bronze badges
1
- 1 Check this demo – Tushar Commented Apr 24, 2016 at 12:49
2 Answers
Reset to default 7This 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./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.
I suppose one might simplify it more by just using the remainder with an offset. This way the entire calculation is done in a single line without any if statements.
var n = 0;
setInterval(function() {
number.innerHTML = 10 - Math.abs(n++ % 20 - 10);
}, 500);
<h1 id="number"></h1>