tags:

views:

86

answers:

2

What is the simplest way to increase a variable by 1 every second?

+2  A: 
var counter = 0;
setInterval(function () {
  ++counter;
}, 1000);

Additionally, if you ever need to turn it off again, this makes that possible:

var counter = 0;
var myInterval = setInterval(function () {
  ++counter;
}, 1000);

// to stop the counter
clearInterval(myInterval);
g.d.d.c
A: 

The simplest way is setInterval("x++",1000);, where x++ can be replaced with your increment. Example:

JavaScript/jQuery

var x=0;

setInterval("x++",1000); // Increment value every second

// Let's just add a function so that you can get the value
$(document).ready(function () {
  $("#showval").click(function(){
    alert(x);
  });
});

HTML

<a href="#" id="showval">Show value</a>
Gert G
`setInterval("x++", 1000);` uses an implied eval(). In most cases that's not a problem, but isn't it technically a security risk?
g.d.d.c
If it was, why haven't they disabled it? It's still the simplest way of increase a variable.
Gert G