Amauri
Amauri

Reputation: 550

How to increment a variable after 1 second in javascript

The goal is to add 1 every second. I am not sure about how to use return here, and how to return the value of secsUp to seconds.

function timeDisp ()
{
var seconds=0;
function changeSecs ()
    {
        var secsUp = seconds+1;
        return secsUp;
    }
document.write(seconds);
}
setInterval(timeDisp,1000);

Upvotes: 2

Views: 2259

Answers (2)

user3256639
user3256639

Reputation: 21

you should store the value of secsUp, in another variable , which is called outside the function. eg- int a= changeSecs(); it will hold the value being returned

Upvotes: 1

Sachin Jain
Sachin Jain

Reputation: 21842

Problems with your code

  1. You have declared a local variable seconds=0 in timeDisp() So the value of seconds will always reset to 0 whenever this method is called.
  2. You are not calling changeSecs() method anytime. I don't see any use of it if you just want to increase 1 to your seconds variable.

Try this jsbin Demo

var seconds=0;
function timeDisp() {
  seconds++;
  document.write(seconds);
}
setInterval(timeDisp,1000);

Upvotes: 2

Related Questions