[英]Javascript adding variable twice
I have the following code: 我有以下代码:
var m = 0;
function addmoney(){
var today = new Date();
var s =today.getSeconds();
if(s == 30){
m += 10;
}
document.getElementById('mon').innerHTML=s+" money: "+m;
t=setTimeout(function(){addmoney()},500);
}
Basically what I'm doing is to add 10 to the value of m every 30 seconds. 基本上我在做的是每30秒将m的值加10。 The problem here is that the variable was actually being added twice. 这里的问题是该变量实际上被添加了两次。 I was wondering why this was the case? 我想知道为什么会这样吗?
EDIT: Sorry did not mean to do s++, eitherways it did not change much. 编辑:对不起并不意味着要做s ++,无论如何它并没有太大变化。
You will want to use window.setInterval 您将要使用window.setInterval
var m = 0,
mon = document.getElementById('mon');
var interval = window.setInterval(function() {
m += 10;
mon.innerHTML = "money: " + m;
}, 30000);
If for whatever reason you would like to stop adding money, you can use window.clearInterval 如果出于任何原因您想停止加钱,可以使用window.clearInterval
// stop collecting monies!
clearInterval(interval);
Add a small change to it 给它添加一个小的变化
if(s == 30 || s == 0)
This is because in the system the seconds counter gets reset to 0 after it crosses 60 这是因为在系统中,秒计数器在超过60后会重置为0。
The reason is that variable s
is being rewritten in time intervals of 500ms (so the s++
trick does not work). 原因是变量s
被以500ms的时间间隔重写(因此s++
技巧不起作用)。 Either increase the interval or use a global variable to store the last time. 增大间隔或使用全局变量存储上次时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.