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