我试图让JS变量随着时间的推移在两个值之间波动。
例如,假设我们从var counter = 0
开始,此变量每秒增加一次。
如何在counter == 3
处将值减少1,直至counter == -3
,此时它再次增加到3,然后再次向下,依此类推。
提前感谢您的帮助!
答案 0 :(得分:1)
你可以这样做:
var counter = 0;
var inc = +1;
setInterval(function(){
if(counter == 3) inc = -1;
if(counter == -3) inc = +1;
counter+= inc;
}, 1000);
请参阅此示例:http://jsfiddle.net/VQFLd/3/
答案 1 :(得分:0)
类似的东西:
var increment = 1;
var counter = 0;
for (var i = 0; i < 100; i += 1) {
counter += increment;
console.log(counter);
if (counter === 3) {
increment = -1;
} else if (counter === -3) {
increment = 1;
}
}
答案 2 :(得分:0)
你可以试试这个
var currentNumber = 0;
var increase = true;
setInterval(function (){changeValues(-3,3);},1000);
function changeValues(minimum,maximum){
if(increase){
if(currentNumber == (maximum-1))
increase = false;
currentNumber++;
}else{
if(currentNumber == (minimum+1))
increase = true;
currentNumber--;
}
}