js 实现倒计时
实现倒计时的基本方法
使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。
使用 setInterval 实现倒计时
通过 setInterval 每秒更新倒计时显示,直到时间为零。
function startCountdown(targetTime, displayElement) {
const countdownInterval = setInterval(() => {
const now = new Date().getTime();
const distance = targetTime - now;
if (distance <= 0) {
clearInterval(countdownInterval);
displayElement.innerHTML = "倒计时结束";
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
displayElement.innerHTML = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
}, 1000);
}
// 示例用法
const targetTime = new Date("2024-12-31").getTime();
const displayElement = document.getElementById("countdown");
startCountdown(targetTime, displayElement);
使用 setTimeout 实现倒计时
通过递归调用 setTimeout 实现倒计时,避免 setInterval 可能带来的累积误差。
function updateCountdown(targetTime, displayElement) {
const now = new Date().getTime();
const distance = targetTime - now;
if (distance <= 0) {
displayElement.innerHTML = "倒计时结束";
return;
}
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
displayElement.innerHTML = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
setTimeout(() => updateCountdown(targetTime, displayElement), 1000);
}
// 示例用法
const targetTime = new Date("2024-12-31").getTime();
const displayElement = document.getElementById("countdown");
updateCountdown(targetTime, displayElement);
优化倒计时显示
可以根据需求调整倒计时显示的格式,例如只显示小时、分钟和秒。
function formatTime(distance) {
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
处理时区问题
如果倒计时涉及跨时区,建议使用 UTC 时间或明确指定时区。
const targetTime = new Date("2024-12-31T00:00:00Z").getTime();
性能考虑
倒计时不需要高精度时,可以将更新频率调整为每秒一次。若需要更高精度,可以缩短间隔时间,但需注意性能影响。







