# loop counting to 100 and back to 0 and up to 100 again and so on

I must admit, I am not a mathematical expert, thats why I cant solve the following problem to my satisfaction.

I have a number, say i=0. I have a function that increases i on each call by 1 and then calls itself again, increasing i another time and another and another ... When reached 100 I want it to count backwards to 0 and then up again, kind of like an endles loop with i going up and down like an elevator. Whats an elegant solution for that?

My solution so far:

var countingUp = true; var i = 0; function count() { if(i < 100 && countingUp) {i+=1} if(i > 1 && !countingUp) {i-=1} if(i===100) {countingUp=false;} if(i===1) {countingUp=true;} count() } count()

I am looking for something shorter.

## Answers

Looks ok to me, but will probably sell your dog into slavery and steal your beer:

var direction = 1; var i = 0; function count() { i += direction; direction *= (((i % 100) == 0) ? -1 : 1); }