今天把之前的倒计时代码修改了一下,以前一直用var声明变量,现在改成const和let,本来以为不会有问题,结果运行时,如果所给时间已经截止,控制台会报错,如图所示,“在初始化之前无法访问countTimer
”
var声明的时候,有变量提升,不会报这个错,所以解决的方法就是提前声明countTimer变量。
把代码
let countTimer = setInterval(countDown, 1000); //报错
作如下修改:
let countTimer; //先声明,不赋值
countTimer = setInterval(countDown, 1000)
今天是4月27日,距离5月1日倒计时,完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style>
div {
margin: 240px
}
span {
display: inline-block;
width: 40px;
height: 40px;
background-color: #342C2D;
font-size: 20px;
color: #fff;
text-align: center;
line-height: 40px;
}
</style>
</head>
<body>
<div>
<span class="day"></span>天
<span class="hour"></span>时
<span class="minute"></span>分
<span class="second"></span>秒
</div>
<script>
// 1. 获取元素
const day = document.querySelector('.day')
const hour = document.querySelector('.hour')
const minute = document.querySelector('.minute')
const second = document.querySelector('.second')
const inputTime = new Date('2025-05-01 00:00:00').getTime() // 返回的是用户输入时间总的毫秒数
let countTimer //先声明,不赋值,这样不会报错
// 2. 开启定时器
countDown() // 先调用一次这个函数,防止第一次刷新页面有空白
countTimer = setInterval(countDown, 1000)
// let countTimer = setInterval(countDown, 1000) //如果初始时间已经截止,会报错
function countDown() {
let nowTime = Date.now()
let times = (inputTime - nowTime) / 1000 // times是剩余时间总的秒数
if (times <= 0) {
clearInterval(countTimer)
day.innerHTML = '00'
hour.innerHTML = '00'
minute.innerHTML = '00'
second.innerHTML = '00'
return
}
let dd = parseInt(times / 86400) //天
dd = dd < 10 ? '0' + dd : dd
day.innerHTML = dd
let hh = parseInt(times / 3600 % 24) //时
hh = hh < 10 ? '0' + hh : hh
hour.innerHTML = hh
let mm = parseInt(times / 60 % 60) // 分
mm = mm < 10 ? '0' + mm : mm
minute.innerHTML = mm
let ss = parseInt(times % 60) // 秒
ss = ss < 10 ? '0' + ss : ss
second.innerHTML = ss
}
</script>
</body>