Reputation: 1521
I have a problem with creating a variable that first will increase value (for example) form 0 to 10, and after that it wil go back from 10 to 0. So 0,1,2,3...10,10,9,8,7...0 (and so on) The main idea looks like this:
var count = 10;
var counter = setInterval(timer, 500);
function timer() {
count = count-1;
if (count == 0) {
count = 10;
}
}
console.log(counter);
But it will only go from 0 to 10 all the time. How to make that 'comeback' thing? Thank you for help.
Upvotes: 1
Views: 8068
Reputation: 23396
I'd use setTimeout()
s instead of setInterval()
, something like this:
var count = 0, dir = 1, end = [0, 10], index = 1, counter,
timer = function () {
console.log(count);
if (count === end[index]) {
dir = -dir;
index += dir;
counter = setTimeout(timer, 500);
return;
}
count += dir;
counter = setTimeout(timer, 500);
};
counter = setTimeout(timer, 500);
And as Bergi stated, works also with setInterval()
:
var count = 0, dir = 1, end = [0, 10], index = 1,
counter = setInterval(function () {
console.log(count);
if (count === end[index]) {
dir = -dir;
index += dir;
return;
}
count += dir;
}, 500);
A live demo with interval at jsFiddle.
The advantage of using a separate end
array is, that you can dynamically change the limits, if needed.
Upvotes: 1
Reputation: 664433
Here's another solution that produces the correct output (with doubled zeros and tens) but is much shorter than @Teemu's one:
var count = 0, step = 1;
var counter = setInterval(function() {
if (count<0 || count>10) // when we're outside the range
count += step *= -1; // change direction and go back into
console.log(count);
count += step;
}, 500);
Upvotes: 2
Reputation: 7771
var count = 10;
var counter = setInterval(timer, 500);
function timer() {
if(!this.diff) this.diff=-1;
count += this.diff;
if(count==0 || count==10) this.diff=-this.diff;
console.log(count);
}
This way, you don't pollute global namespace.
Upvotes: 0
Reputation: 953
Here is another solution as I understood :
var count = 0;
var flag = false;
setInterval(function(){timer()}, 500);
function timer() {
console.log(count);
if (flag){
count = count - 1;
}
if(!flag){
count = count + 1;
}
if (count =< 0) {
flag=false;
}
if (count >= 10) {
flag = true;
}
}
Upvotes: 1
Reputation: 125
Try to change the increment value
var count = 10;
var counterIncrement=-1;
var counter = setInterval(timer, 500);
function timer() {
count = count+counterIncrement;
if (count == 0 || count == 10 ) {
counterIncrement = -counterIncrement;
}
console.log(count);
}
Upvotes: 2
Reputation: 325
The problem that I see there is that in the line
var counter = setInterval(timer, 500);
setInterval is returning you an ID that you can then use to call clearInterval and stop the sequence of calls to timer(). It is not returning you the value of count.
What you want, IMHO is something like this:
var counter = 10;
setInterval(function() {
counter = counter - 1;
if (counter < 0) {
counter = 10;
}
console.log(counter);
}, 500);
Upvotes: 0