klamertd klamertd - 7 months ago 22
Javascript Question

increase value until limit then decrease loop

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);

Answer

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.