Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 624
klamertd Avatar asked Nov 17 '25 12:11

klamertd


1 Answers

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.

like image 131
Tamas Hegedus Avatar answered Nov 19 '25 04:11

Tamas Hegedus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!