0

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. 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.

4
  • 4
    FYI, setTimeout(function(){addmoney()},500) is simpler written as setTimeout(addmoney,500) Commented Dec 2, 2013 at 8:46
  • when and how do you call addmoney() for the first time? Commented Dec 2, 2013 at 8:48
  • 1
    You set your timeout function to call after 0.5 seconds. getSeconds() only returns full seconds. So if you call the function at e.g. 12:30:01 100ms which returns 30sec and the next call resolves fast enough the next date could be 12:30:01 700ms which also returns 30sec m gets increased twice at this point of time...to be on the safe side, set timeout to 1000ms ;) Commented Dec 2, 2013 at 8:48
  • @Igle Thanks for the explanation, I was wondering what was wrong with it. The timeout trick you gave me definitely also fixed the problem! Commented Dec 2, 2013 at 8:52

3 Answers 3

5

You will want to use 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

// stop collecting monies!
clearInterval(interval);

Here's a jsbin.com demo

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you. I will accept the answer once I am able to.
0

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

Comments

0

The reason is that variable s is being rewritten in time intervals of 500ms (so the s++ trick does not work). Either increase the interval or use a global variable to store the last time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.