#谁能解释为什么这一段JavaScript代码不能够被正确执行?
#这段代码是关于。setInterval
#我想显示每隔一秒钟让它自动更新一下时间。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ff</title>
</head>
<body>
<p id="d">0</p>
<script>
var a=new Date()
var c=a.getSeconds()
setInterval(function(){document.getElementById("d").innerHTML =a.getSeconds(); }, 1000);
</script>
</body>
</html>
把时间获取也放到 回调函数里面,不然更新的都是同一个值
setInterval(function(){
var a=new Date();
var c=a.getSeconds();
document.getElementById("d").innerHTML = a.getSeconds();
}, 1000);
同样的,我们也可以清除setInterval()
定时器的效果,语法为:
window.clearInterval(intervalID);
clearInterval()方法取消了先前通过调用 setInterval()
建立的定时器。
注意:
比如我们现在有两个按钮,点击一个可以开启定时器,点击另一个可以清除该定时器,操作方法为:
<body>
<button class='begin'>开始</button>
<button class='stop'>停止</button>
<script>
var btn = document.querySelectorAll('button');
var timer = null;
btn[0].addEventListener('click',function(){
timer = setInterval(function(){
console.log('你好');
},1000)
})
btn[1].addEventListener('click',function(){
clearInterval(timer)
})
</script>
</body>
运行效果为: