倒计时效果

今天把之前的倒计时代码修改了一下,以前一直用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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值