简体   繁体   中英

How to add a number every one second so I can show or use them later?

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>
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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM