someguyMTofficial
someguyMTofficial

Reputation: 23

how to count up a var and count back again javascript

I have a var which I tried to make the value of it count up till 100. When it reaches 100 it should count back to 0. this is my experimentation code.

var min = 0 - 1,
max = 100 + 1, 
now = 0;
var timer = setInterval(function(){
    if(now <= max){
        now++;
        console.log(now);
    }else if ( now >= min){
        now--;
        console.log(now);
    }
},500);

The code works till it counts up to 100, but it doesn't count it back to 0, and repeat the same process over and over again.

Can anyone give me a clue what I am doing wrong, or if I'm doing it completely wrong. Can you please explain the method I should use?

Upvotes: 1

Views: 2403

Answers (3)

adilu
adilu

Reputation: 141

Use a variable step = +1; which will change to step = -1; as soon as you reach the maximum:

var min = 0,
    max = 100,
    step = +1,
    now = 0; 

var timer = setInterval(function(){
    if(now >= max) {step = -1;}
    if(now <= min) {step = +1;}
    now += step;
    console.log(now);
}, 20);

Upvotes: 5

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

try this please:

var count = 'up';
var min = 0 - 1,
max = 100 + 1, 
now = 0;
var timer = setInterval(function(){
    if(count === 'up'){
        if(now <= max){
           now++;
        }
        else{
           count = 'down';
           now--;
        }
    }
    else{
       if(now >= min){
           now--;
        }
        else{
           count = 'up';
           now++;
        }
    }
    console.log('now: ' + now);
},500);

Try this demo (count until 10 to reduce time of execution)

DEMO

Upvotes: 2

N4ppeL
N4ppeL

Reputation: 1847

just think about what you are doing. When the count is up on 101, it does not count up because the if statement is false. so you decrease back to 100. But in the next loop, the first if statement is true again and you increase.

You could set a flag the first time you decrease, and add the flag into the first if condition, meaning, once the flag is set you never increase the value again.

Upvotes: 0

Related Questions