Javascript 整数加 1;每 1 秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10586890/
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
Increment integer by 1; every 1 second
提问by JHarley1
My aim is to create identify a piece of code that increments a number by 1, every 1 second:
我的目标是创建一段代码,每 1 秒将数字增加 1:
We shall call our base number indexVariable, I then want to: indexVariable = indexVariable + 1 every 1 second; until my indexVariable has reached 360 - then I wish it to reset to 1 and carry out the loop again.
我们将调用我们的基数 indexVariable,然后我想: indexVariable = indexVariable + 1 每 1 秒;直到我的 indexVariable 达到 360 - 然后我希望它重置为 1 并再次执行循环。
How would this be possible in Javascript? - if it makes a difference I am using the Raphael framework.
这在 Javascript 中怎么可能?- 如果它有所作为,我正在使用 Raphael 框架。
I have carried out research of JavaScript timing events and the Raphael delay function - but these do not seem to be the answer - can anyone assist?
我已经对 JavaScript 计时事件和 Raphael 延迟函数进行了研究 - 但这些似乎不是答案 - 任何人都可以提供帮助吗?
回答by Christoph
You can use setInterval()
for that reason.
setInterval()
出于这个原因,您可以使用。
var i = 1;
var interval = setInterval( increment, 1000);
function increment(){
i = i % 360 + 1;
}
edit: the code for your your followup-question:
编辑:您的后续问题的代码:
var interval = setInterval( rotate, 1000);
function rotate(){
percentArrow.rotate(1,150,150);
}
I'm not entirely sure, how your rotate works, but you may have to store the degrees in a var and increment those var too like in the example above.
我不完全确定您的旋转是如何工作的,但是您可能必须将度数存储在 var 中,并像上面的示例一样增加这些 var。
回答by Joe
var indexVariable = 0;
setInterval(function () {
indexVariable = ++indexVariable % 360 + 1; // SET { 1-360 }
}, 1000);
回答by chrisdotcode
Try:
尝试:
var indexVariable = 0;
setInterval(
function () {
indexVariable = (indexVariable + 1) % 361;
}, 1000}