setInterval语法规范:
window.setInterval(调用函数,延时时间);
与setTimeout区别:
setTimeout是延时时间到了就去调用这个回调函数,只调用了一次 就结束了这个定时器。
setInterval是 每隔这个延迟时间 就去调用这个回调函数 会调用很多次 重复调用这个函数。应用在网页中的一些轮播图上。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
setInterval(function() {
console.log('继续输出');
},1000);
</script>
</body>
</html>
京东倒计时例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #2F3430;
line-height: 50px;
text-align: center;
color: #FFF;
font-size: 20px;
}
</style>
</head>
<body>
<div class="box">
<span class="hour">
1
</span>
<span class="minute">
2
</span>
<span class="second">
3
</span>
</div>
<script type="text/javascript">
var hour = document.querySelector('.hour');
var minute = document.querySelector('.minute');
var second = document.querySelector('.second');
var inputTime = +new Date('2022-3-29 08:00:00');
countDown();
setInterval(countDown, 1000);
function countDown() {
var nowTime = +new Date();
var times = (inputTime - nowTime) / 1000;
var h = parseInt(times / 60 / 60 % 24); //时
h = h < 10 ? '0' + h: h;
hour.innerHTML = h; //把剩余的小时给 小时黑色盒子
var m = parseInt(times / 60 % 60); //分
m = m < 10 ? '0' + m: m;
minute.innerHTML = m;
var s = parseInt(times % 60); //秒
s = s < 10 ? '0' + s: s;
second.innerHTML = s;
}
</script>
</body>
</html>