Reputation: 517
I was wondering if anyone can help me. As I wrote in the titel I need to have an opportunity to add a number every one second to my var "number". And I'd like to use them in the future, for example: in an egg timer (as a number you substract from). What do I do wrongly? Thanks for help :)
Here's my code:
<!DOCTYPE html>
<html style="height: 100%;">
<head></head>
<body>
<p id="time"></p>
<button onclick="show()">show me</button>
<script type="text/javascript">
var number = 0
clock();
function clock(){
clock2 = setInterval(function() {
number + 1;
}, 1000);
}
function show(){
document.getElementById("time").innerHTML = number;
}
</script>
</body>
</html>
Upvotes: 0
Views: 22
Reputation: 138277
number + 1;
must be
number += 1;
Your expression is going into the nowhere of the JS parser...
Also this:
clock();//bad style
function clock(){
clock2 = setInterval(function() {
number += 1;
}, 1000);
}
can be brewed down to this:
(function (){
setInterval(function(){
number+=1;
},1000);
})()
And if you want to stop/restart it, you may make it more elegant trough this:
var stop=false,
timer=null;
function start(){
timer=timer||setInterval(function(){
if(stop){
destroyInterval(timer);
timer=null;
stop=false;
return;
}
number+=1;
},1000);
}
Use like this:
start();
start();//will do nothing
stop=true;//stops timer
if(!timer){
start();
}
Upvotes: 1