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
2010-06-15 22:34:21
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
2010-06-15 22:44:47
`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
2010-06-15 22:49:53
If it was, why haven't they disabled it? It's still the simplest way of increase a variable.
Gert G
2010-06-15 22:55:25