我想知道是否有人可以帮助我。正如我在标题中写的那样,我需要有机会每隔一秒向我的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>
答案 0 :(得分:2)
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();
}