增加和减少一个变量,直到在 javascript 中达到一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5496576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increase and decrease a variable until a number is reached in javascript
提问by Carlos Barbosa
how can I increase and decrease a variable in javascript until 100 and when 100 is reached it should start decreasing.
如何在 javascript 中增加和减少变量直到 100,当达到 100 时它应该开始减少。
So accuracyBarValue should start in 0, increase to 100, and when 100 is reached it should go to 0, and then repeat procedure.
所以accuracyBarValue应该从0开始,增加到100,当达到100时它应该去0,然后重复这个过程。
This in intervals of 10.
这以 10 为间隔。
I use this in a very simple JS game, where this value is used to increase and decrease a PowerBar.
我在一个非常简单的 JS 游戏中使用它,该值用于增加和减少 PowerBar。
Thanks in advance.
提前致谢。
回答by codingbadger
Here is another take on this:
这是另一种看法:
var up = true;
var value = 0;
var increment = 10;
var ceiling = 100;
function PerformCalc() {
if (up == true && value <= ceiling) {
value += increment
if (value == ceiling) {
up = false;
}
} else {
up = false
value -= increment;
if (value == 0) {
up = true;
}
}
document.getElementById('counter').innerHTML = 'Value: ' + value + '<br />';
}
setInterval(PerformCalc, 1000);
<div id="counter"></div>
回答by Damb
回答by Joshua Pinter
Using Duration and Frame Rate.
使用持续时间和帧速率。
Another approach that allows you to specify the duration and frame rate. Highly useful for animations and things that happen over a period of time.
另一种允许您指定持续时间和帧速率的方法。对于动画和一段时间内发生的事情非常有用。
HTML
HTML
<h2>Increment Value over a Duration with a given framerate</h2>
Value: <span id="value">0</span>
JavaScript
JavaScript
var valueElement = document.getElementById('value');
var start = 0;
var end = 100;
var duration = 10000; // In milliseconds (divide by 1000 to get seconds).
var framerate = 50; // In milliseconds (divide by 1000 to get seconds).
var toAdd = ( ( end - start ) * framerate ) / duration;
var interval = setInterval(function() {
var currentValue = parseFloat(valueElement.innerHTML);
if (currentValue >= end) {
clearInterval(interval);
return;
}
valueElement.innerHTML = (!isNaN(currentValue) == true ? currentValue + toAdd : toAdd);
}, framerate);
JSFiddle
JSFiddle
https://jsfiddle.net/joshuapinter/8uasm7ko/
https://jsfiddle.net/joshuapinter/8uasm7ko/
I wanted to display the incremental value but you could easily wrap this up into a generic function as well.
我想显示增量值,但您也可以轻松地将其包装为通用函数。
回答by rockerest
var i = 0;
while( i < 100 )
{
i++;
}
while( i > -1 )
{
i--;
}
You can also do other code in the while
loops, obviously.
while
显然,您还可以在循环中执行其他代码。