【问题标题】:How to add a number every one second so I can show or use them later?如何每隔一秒添加一个数字,以便以后显示或使用它们?
【发布时间】:2017-04-16 14:26:48
【问题描述】:

我想知道是否有人可以帮助我。正如我在标题中所写的那样,我需要有机会每隔一秒将一个数字添加到我的 var“数字”中。我想在将来使用它们,例如:在一个鸡蛋计时器中(作为你减去的数字)。我做错了什么?感谢您的帮助:)

这是我的代码:

<!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>

【问题讨论】:

    标签: javascript html numbers add


    【解决方案1】:
    number + 1;
    

    必须

    number += 1;
    

    您的表达式将进入 JS 解析器的无处...

    还有这个:

    clock();//bad style
    function clock(){
    clock2 = setInterval(function() {
        number += 1;
    }, 1000);
    }
    

    可以归结为:

    (function (){
       setInterval(function(){
          number+=1;
       },1000);
     })()
    

    如果您想停止/重新启动它,您可以通过以下方式使其更优雅:

    var stop=false,
    timer=null;
    function start(){
       timer=timer||setInterval(function(){
          if(stop){
              destroyInterval(timer);
              timer=null;
              stop=false;
              return;
           }
        number+=1;
      },1000);
    }
    

    这样使用:

    start();
    start();//will do nothing
    stop=true;//stops timer
    if(!timer){
      start();
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 2020-07-14
      • 2023-04-09
      • 1970-01-01
      • 2012-06-01
      • 2018-11-02
      • 2018-11-17
      • 2017-05-20
      • 2022-10-19
      相关资源
      最近更新 更多