javascript - 如何每秒添加一个数字,以便稍后显示或使用它们?

标签 javascript html numbers addition

我想知道是否有人可以帮助我。正如我在标题中所写,我需要有机会每秒向我的 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>

最佳答案

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

关于javascript - 如何每秒添加一个数字,以便稍后显示或使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43438252/

相关文章:

javascript - 将一组重叠范围划分为一组非重叠范围

algorithm - 比较乘法

javascript - Angular js 绑定(bind)不起作用

javascript - 更新 php 变量并在页面刷新时选择选项

javascript - 带有 id 参数的 AngularJS 路由以白页结束

javascript - 如何找到以前点击的类/元素 - jquery

javascript - $http GET 刷新页面

php - 使用 PHP 的 HTML DOMDocument 解析 HTML

c - C 中的素数

android - HTML5 - Android 平板电脑 - 输入类型编号